1. Java Error类与Exception类的区别
Error:致命异常。标识系统发生了不可控的错误。程序无法处理,只能人工介入。例如, 虚拟机产生的错误StackOverflowError、OutOfMemoryError。
Exception:非致命异常。程序可处理。分为受编译器检测的checked异常(受检异常)和不受编译器检测的unchecked异常(非受检异常)。
2.Unchecked异常与Checked异常
ArithmeticException | int a=0; int b= 3/a; |
ClassCastException: | Object x = new Integer(0); System.out.println((String)x); |
IndexOutOfBoundsException ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException | int [] numbers = { 1, 2, 3 }; int sum = numbers[3]; |
IllegalArgumentException NumberFormatException | int a = Interger.parseInt("test"); |
NullPointerExceptionextends |
除去Unchecked异常,其他异常均是Checked异常,例如:ActivationException, AlreadyBoundException, ApplicationException, AWTException
3.异常处理
例如:
显式异常声明
程序捕获处理:
4.异常中的throws声明与throw语句的区别
1)throws 关键字用于声明异常,其位置是方法头部的最后,方法体开始的 { 之前。
2)throw 关键字则用来抛出异常,其位置是方法体中。
3)throw和throws关键字之间的联系:如果在某方法中使用throw抛出了某种 unchecked exception而该throw语句并未使用 try-catch结构进行异常处理,则throw语句所在的方法必须使用throws关键字进行该异常类的声明,否则产生编译错误。
5. finally 子句的作用
是这个组合语句的统一出口,一般用来进行一些善后清理操作,例如清理资源、释放连接、关闭文件、管道流等操作。它是可选的部分,但一旦选定,必定执行。
例如:
public class TestFinally {
public static void main(String[] args) {
System.out.println(testFinally());
}
private static int testFinally() {
int temp = 100;
try {
System.out.println("Try");
return ++temp;// return的结果被暂存
}
finally {
temp = 1;
System.out.println( "Finally" );
}}}
结果为:
Try
Finally
101
finally代码块在return语句运行后执行的。return结果被暂存,等finally代码块执行结束后再将之前暂存的结果返回