概念
1.try
如果在一个方法内部出现了异常(或者在方法内部调用的其他方法抛出了异常),这个方法将在抛出异常的过程中结束。
异常处理理论上有两种基本模型。终止模型和恢复模型。个人理解回复模型类似于中断处理。而java支持终止模型,这种模型中,程序无法返回异常发生的地方继续执行。
要是不希望方法就此结束,可以在方法内设置一个特殊的块来捕获异常,成为try块。
2.catch
对于抛出的异常必须在某处得到处理,异常处理程序以关键字catch表示,紧跟在try后。
3.finally
有一些代码希望无论有没有异常抛出都能够执行,可以在catch后面加finally子句。
4.结构
try{
}catch{
}finally{
}
5.执行顺序
a.抛出异常处理顺序
public class TestException {
public static void main(String[] args) {
TestException testException1 = new TestException();
int i=1;
try {
i=2;
System.out.println("in try");
testException1.fun();
System.out.println("end try");
} catch (Exception e) {
System.out.println("in catch");
} finally{
i=3;
System.out.println("in finally");
}
System.out.println("the end i="+i);
}
public void fun() throws Exception{
throw new Exception();
}
}
输出结果:
in try
in catch
in finally
the end i=3
可以看到testException1.fun();抛出异常以后,代码跳出try块转到catch执行异常处理程序,然后继续执行finally程序。最后顺序执行System.out.println("the end i="+i);如果没有try块的话,整个方法都会跳出。
b.不抛出异常处理顺序
public class TestException {
public static void main(String[] args) {
TestException testException1 = new TestException();
int i=1;
try {
i=2;
System.out.println("in try");
//testException1.fun();
System.out.println("end try");
} catch (Exception e) {
System.out.println("in catch");
} finally{
i=3;
System.out.println("in finally");
}
System.out.println("the end i="+i);
}
public void fun() throws Exception{
throw new Exception();
}
}
结果输出:
in try
end try
in finally
the end i=3
可以看到不管异常抛不抛出,finally语句都会执行。