Throwable下有两种,一种是Error错误类,另一种是Exception异常类。
异常exception又分为运行时异常和非运行时异常
常见的4中运行时异常
-
ClassCastException(类转换异常)
-
IndexOutOfBoundsException(数组越界)
-
NullPointerException(空指针)
-
ArithmeticExceptio(除数为0)
运行时异常是在运行中出现的,在编译时是不会报错的,当你throw一个运行时异常时,不在方法外添加throws编译器也不会发生报错。
Throw:手动抛出异常
Throws:用在方法后面声明可能会抛出的异常
异常处理机制-try-catch-finally
如果异常出现,程序没有将其处理,那么程序就会中断,于是用异常处理机制-try-catch-finally。
try{
//可能发生异常的代码
}catch(){
//处理异常的代码
}finally{
//无论是否发生异常都会执行的代码,常用于程序资源的回收处理
}
-try-catch-finally中可以有多个catch也可以没有catch,但try必须和catch或者finally搭配使用。
dasda
-
不要把所有的代码都写到try里面,try里面的代码执行时,系统维护堆栈跟踪信息,执行效率低
-
catch是捕捉异常的,顺序执行,所有不要把父类异常放在子类异常的上面,否则报错。如果catch里没有捕捉到当前的异常,那么程序还是会中断
-
finally里的代码,不管异常是否捕捉都一定会执行。例io流中的close()方法一般都放到finally里进行,finally于return也是个坑点。
finally&&return
try {
System.out.println("try "+i);
return i;
}finally{
++i;
System.out.println("finally "+i);
}
}
System.out.println(test());
System.out.println(i);
System.out.println("-----------------");
finally 1
0
1
-----------------
try {
System.out.println("try "+i);
return i;
}finally{
++i;
System.out.println("finally "+i);
}
}
System.out.println(test());
System.out.println(i);
System.out.println("-----------------");
finally 1
1
1
-----------------
int c = 0;
try {
c = 5 / 0;
System.out.println(5 / 0);
return 0;
} catch (NullPointerException e) {
System.out.println("空指针异常");
} finally {
System.out.println("finally");
}
return c;
}
System.out.println(test02());
System.out.println("test02 over");
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.z.exception.Return1.test02(Return1.java:19)
at com.z.exception.Return1.main(Return1.java:35)
try {
System.out.println(5 / 0);
return 0;
} catch (NullPointerException e) {
} finally {
System.out.println("finally");
return 0;
}
}
System.out.println(test01());
System.out.println("test01 over");
System.out.println("---------------------");
0
test01 over
---------------------
要注意的是,当finally有return时:
-
它会覆盖try,catch中的return,方法返回的都将是finally中的
-