别名 XF
最近在看了一些改善代码的原则,重温下基础,而又不可忽视的重点区域,记录下来。
认识异常流执行机制
异常流类似于goto语句,java中没有goto语句,但是异常采用了类似的技术。一旦一个异常诞生,控制流(control)就会立刻转入下面三者之一
catch block (捕获区段)
finally block (终结区段)
calling method (调用端)
选明确代码中出现异常时执行的顺序
public class ExceptionTest {
public static void main(String[] args) {
System.out.println("Extering main()");
ExceptionTest et = new ExceptionTest();
try {
System.out.println("Calling m1()");
et.m1();
System.out.println("Returing form call to m1()");
}catch (Exception e ){
System.out.println("Caught IOException in main()");
}
System.out.println("Enterint main()");
}
public void m1() throws Exception{
System.out.println("Entering m1()");
try {
System.out.println("Calling m2");
m2();
System.out.println("Returing form call to m2()");
System.out.println("Calling m3");
m3(true);
}catch (Exception e){
System.out.println("Caught IOException in"+"m1()...rethrow");
throw e;
}finally {
System.out.println("In finally for m1()");
}
System.out.println("Exiting m1()");
}
private void m2() {
System.out.println("Entering m2()");
try {
Vector v = new Vector(5);
}catch (IllegalArgumentException e){
System.out.println("Caught IllegalArgumentException in"+"m2()");
}finally {
System.out.println("In finally for m2()");
}
System.out.println("Exiting m2()");
}
private void m3(boolean b) throws IOException{
System.out.println("Entering m3()");
try {
Button b3 = new Button();
if(b){
throw new IOException();
}
} finally {
System.out.println("In finally for m3()");
}
System.out.println("Exiting m3()");
}
}
输出结果
Extering main()
Calling m1()
Entering m1()
Calling m2
Entering m2()
In finally for m2()
Exiting m2()
Returing form call to m2()
Calling m3
Entering m3()
In finally for m3()
Caught IOException inm1()...rethrow
In finally for m1()
Caught IOException in main()
Enterint main()
- 代码复制执行一遍就可以看出异常的执行过程
主函数进入m1()方法,m1中包含的m3()方法抛出异常后,会进入m1()方法的catch中,m1在往外抛出异常,
会进入主函数的catch中。
在try区域内抛出异常时将会发生:
如果同时存在catch和finally区,则控制流会先转移到catch区,在转移到finally区
如果没有catch区,控制流会转移到finally。
- 不积跬步,无以至千里 每天一点点。