一,异常 :
什么是异常 :
程序生病了,非正常可以执行完毕|编译期间就检测出的问题
异常一旦出现: 1)程序无法执行 2)终止程序的继续执行,抛出异常的信息展示给程序猿
二,异常的体系 :
Throwable : 类是Java语言中所有错误和异常的超类。
/ \
Error Exception
Error : 一般是由虚拟机生成并脱出的,不由程序猿控制
Exception : 异常
CheckedException检查时异常|编译时异常 :
发生在程序需编译期间,如果程序猿不处理程序无法运行 ---->通过异常的处理方案(2种)
//java.io.FileNotFoundException文件没找到异常--->编译时异常
InputStream is = new FileInputStream("D://test.txt");
RuntimeException运行时异常 :
发生在程序运行期间,不处理程序终止执行 --->通过异常的处理方案(2种) | 增强程序健壮性if (推荐)
常见的运行时异常
java.lang.NullPointerException :空指针异常
java.lang.ArrayIndexOutOfBoundsException :数组下标越界异常
java.lang.ArithmeticException:数学异常
java.lang.ClassCastException:类转换异常
三,异常处理方案 : *****
异常抛出 :
throws 可以实现抛出多个异常,跑到上一层,由调用者解决处理
异常捕获 :
try{
有可能出现异常的代码段;
}catch(异常类型 引用){
捕获了对应类型异常后执行的代码;
}.....
finally{
无论是否出现异常都会执行的代码段...
一般定义资源的关闭等代码;
}
try {
System.out.println("try开始了");
//数学异常
//检测到异常之后不再执行try后面的代码直接进入catch
System.out.println(5/0);
FileInputStream src=new FileInputStream("D:\\src.txt");
System.out.println("try结束了");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
e.printStackTrace();
System.out.println("getMessage====");
System.out.println(e.getMessage());
}catch(ArithmeticException e){
System.out.println("ArithmeticException===");
e.printStackTrace();
System.out.println();
}finally {
System.out.println("不太饿,但是点了外卖的漂亮女人");
}
如果try中的代码从上到下执行没有遇到异常,catch不会执行
如果try中代码一旦遇到异常,try后面的代码不再执行,从上到下执行catch判断哪一个catch所捕获的异常类型满足,执行对应的catch后的语句体
一个try后面可以接1~n个catch
接收异常类型范围较大的catch放在后面
四,自定义异常->了解
异常也是类,需要继承自异常体系
如果直接或者间接的继承自RuntimeException,当前异常类为运行时异常
如果直接继承自Exception,或者没有继承RuntimeException,继承了Exception其他子类,这样异常为一个编译时异常
throw制造异常
//继承了运行时异常,可以用简单的增强程序健壮性避免异常
class AgeException extends RuntimeException{
public AgeException(){}
public AgeException(String str){
super(str);
}
}
public Student(String name, int age) {
this.name = name;
if(age<18){
//要用throw抛出异常
throw new AgeException();
}
this.age = age;
}