异常
在Java中,将程序执行过程中发生的不正常行为称为异常。
分类: 检查性异常、运行时异常、错误
异常的体系:
Java 把异常当做对象来处理,并定义一个基类 java.lang。Throwable 作为所有异常的超类 。(最顶层的类)
关键字: try 、catth 、finally 、 throw 、throws
(一)异常的捕获:
代码举例:
public class Demo01 {
public static void main(String[] args) {
int a = 10;
int b = 0;
try { //try监控区域
System.out.println( a/b );
} catch (Exception e) { // catch 想要捕获的异常类型
System.out.println("Error");
} finally { //处理善后工作,也可以不要 通常在finally中处理IO、资源及关闭等操作,此处一定会执行
System.out.println("finally");
}
使用快捷键生成
//可以使用Ctrl + Alt + t 快速生成 try catch finally语句,选中要监控的语句,按下快捷键,选择try catch finally
try {
System.out.println( a/b );
} catch (Exception e) {
e.printStackTrace(); //此处可以打印错误的栈信息
} finally {
System.out.println("finally");
}
}
}
try catch 语句与 if else 语句类似,允许嵌套,但范围应该按照从小到大的顺序
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println( a/b );
} catch (Exception t) {
System.out.println("Exception");
} catch (Error m) {
System.out.println("Error");
} catch (Throwable n) {
System.out.println("Throwable");
}
finally {
System.out.println("finally");
}
}
}
(二)主动抛出异常 :
- throw :主动在抛出异常,通常用在方法中
public class test02 {
public static void main(String[] args) {
int a = 20;
int b = 0;
new test02().div(a,b);
}
public void div(int a,int b) {
if( b== 0) {
throw new ArithmeticException();//主动抛出异常,一般用在方法中
}
}
}
运行结果
- throws : 如果在方法中处理不了该异常,可以使用 throws 关键字将该异常抛出到更高一级中处理
public class test02 {
public static void main(String[] args) {
int a = 20;
int b = 0;
try { //此处捕获 div 方法中抛出的异常,可以使程序不终止继续运行,而后在这个语句中处理该异常
new test02().div(a,b);
} catch (ArithmeticException e) {
System.out.println("异常");
} finally {
System.out.println("finally");
}
System.out.println("继续执行");
}
public void div(int a,int b) throws ArithmeticException {
if( b== 0) {
throw new ArithmeticException();//throw关键字:主动抛出异常,一般用在方法中
}
}
}
运行结果:
可以看到 最后一条语句被执行了,说明异常被捕获了。