当在捕获Exception时,如果有finally块,且在finally中有return 语句,程序的运行flow该会是怎样的呢?我们直接写给例子来演示,
再总结分析。
package test;
/**
* Created by xieguojun on 14-12-26.
*/
public class ExceptionDemo {
public static void main(String[] args){
int res = test();
System.out.print(res);
}
public static int test(){
try{
System.out.print("a");
try{
promblem();
return 1;
}
finally {
System.out.print("g");
return 2;
//throw new RuntimeException();
}
}catch (RuntimeException re){
System.out.print("d");
return 3;
}catch (Exception e){
System.out.print("e");
}
finally {
System.out.print("f");
return 4;
}
}
private static void promblem() {
throw new RuntimeException();
}
}
程序会打印出agf4
分析:
1.当java方法中的代码执行到return时,会在return执行之前检查该代码块是否被包裹在finally块中,如果有的话,则先执行finally块(块中没有return),如果该finally块的外层还有finally块,则继续跳到外层的finally块中执行(块中没有return),以此类推,最后返回到try块中执行return 语句。
2.如果finally块中也有return语句,则执行finally块中的return语句,如果该finally块被包裹在另一个finally块中,则跳到上层finally块,执行上层finally块中的return语句。上述例子就是最终返回的最外层的finally块的return语句,结果为4.