在使用finally时想到一个问题,如果在try...catch语句中有return语句,思考它跟finally语句的执行顺序。
撸码试试:
package javaTest;
public class ReturnTest {
public static final int test2(){
try {
int i = 1 / 0 ;
} catch (Exception e) {
System.out.println("before");
return test1();
}finally{
System.out.println("finally");
}
return 0;
}
public static int test1(){
System.out.println("after");
return 100;
}
public static void main(String[] args) {
test2();
}
}
执行结果如下:
before
after
finally
看来是return 语句比finally语句先执行。
如果return 语句换成System.exit(0);呢?再撸一撸:
package javaTest;
public class ReturnTest {
public static final void test(){
try {
int i = 1 / 0 ;
} catch (Exception e) {
System.out.println("before");
System.exit(0);
}finally{
System.out.println("finally");
}
}
public static void main(String[] args) {
test();
}
}
结果只打印before,说明finally语句在System.exit(0);正常退出时不会被执行。