在try catch finally 中不管try catch 中有没有return 都会执行finally 并且return的值会先执行但是将值保存起来,等finally执行结束返回结果,不管finally是否改变值,返回结果不变。
public static void main(String[] args) {
int b = test();
System.out.println(b);
}
public static int test() {
int x = 1;
try {
return x++;
}catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("finally:" + x);
++x;
System.out.println("++x:" + x);
}
return x;
}
运行结果:
finally:2
++x:3
1
本文探讨了在Java中try-catch-finally语句块内return语句的执行顺序。即使try或catch中有return,finally块也会被执行,且finally中的操作不会影响return的值。通过一个示例程序展示了这一特性,程序输出表明最终返回的值是在try或catch中确定的,不受finally中代码的影响。

496

被折叠的 条评论
为什么被折叠?



