finally是必须执行的语句块,即便try或者catch有返回。但是测试过其实try或者catch里面的return是先执行的,只是结果缓存了,没有跳转,而是到了finally语句块。
来两段代码记录下
public class App
{
public static void main( String[] args )
{
System.out.println("P2: " + new App().test());
}
public int test() {
int i = -5;
int j = 0;
try {
throw new Exception("xx");
} catch (Exception e) {
return j++;
} finally {
System.out.println("P1: " + i + " " + j);
}
}
}
// 输出
P1: -5 1
P2: 0
j++运行了,返回值是0暂存在方法栈中,然后强制跳转到finally,此时j已加1。输出P1,结束finally后,如果finally里面没有return,则原catch返回0。
当然如果try或者catch里面有system.exit(0);会直接退出,不进入finally
public class App
{
public static void main( String[] args )
{
System.out.println("P2: " + new App().test());
}
public int test() {
int i = -5;
int j = 0;
try {
return i++;
// throw new Exception("xx");
} catch (Exception e) {
return j++;
} finally {
System.out.println("P1: " + i + " " + j);
}
}
}
// 输出
P1: -4 0
P2: -5
类似
博客介绍了try-catch-finally语句块的执行规则。finally语句块无论如何都会执行,即便try或catch中有返回,不过try或catch里的return会先执行,结果缓存。若finally无return,原catch返回缓存结果。若有system.exit(0),则直接退出,不进入finally。

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



