周五和同事讨论了一个比较常见的问题,try代码段中包括了return,finally代码块还是否执行,测试代码如下:
package testJava;
public class Apple {
public static void main(String[] args){
testTry();
}
public static void testTry(){
try{
System.out.println("In the try code!");
return;
}catch(Exception e){
//
}
finally{
System.out.println("In the finally code!");
}
}
}
执行输出果如下:
In the try code!
In the finally code!
从以上测试代码可以推断出finally代码块会在return语句之前执行。
但是并不是所有情况finally都能够得到执行的,看如下代码:
package testJava;
public class Apple {
public static void main(String[] args){
testTry();
}
public static void testTry(){
try{
System.out.println("In the try code!");
System.exit(1);
return;
}catch(Exception e){
//
}
finally{
System.out.println("In the finally code!");
}
}
}
执行结果如下:
In the try code!