finally和return谁先执行
正确答案
下面是我查看多篇博客后找到的正确答案
- finally块的语句在try或catch中的return语句执行之后返回之前执行
- 且finally里的修改语句可能影响也可能不影响try或catch中 return已经确定的返回值
- 若finally里也有return语句则覆盖try或catch中的return语句直接返回。
怎么验证
下面是我验证答案用的程序
public class ExceptionTest {
public static void main(String[] args) {
int x=test();
System.out.println(x);
}
private static int test() {
int a=1;
try {
// int x=1/0;
return a;
}catch (ArithmeticException e){
System.out.println(e);
a=2;
return a;
}finally {
a=3;
System.out.println("finally语句执行-----");
// return a;
}
}
}
至于详细的验证就不多说了
主要是用上面的程序加断点,或者注释掉一两行代码来验证啦,自己动手多跑几遍代码应该能搞清楚的