遇到个很有意思的问题,Java 的 catch 块里有 return 语句执行时,finally 块里的语句会执行吗?执行顺序是怎样的?
虽然平时很少这样写,但这是个值得思考的问题,这篇博客就来求证一下。
场景一:return x,返回只有一个引用
public class Test {
public static void main(String[] args) {
int back = Test.test();
System.out.println(back);
}
public static int test() {
int x = 0;
try {
throw new Exception();
} catch (Exception e) {
return x;
} finally {
System.out.println("执行finally块");
}
}
}
执行上述代码,得到结果:
执行finally块
0
可以看出来先执行的 finally 块的语句,再返回到调用者。
场景二:return x = x + 1,返回的是一个计算赋值语句
对上述代码稍做修改:
public class Test {
public static void main(String[] args) {
int back = Test.test();
System.out.println(back);
}
public static int test() {
int x = 0;
try {
throw new Exception();
} catch (Exception e) {
return x = x + 1;
} finally {
System.out.println(x);
}
}
}
执行上述代码,得到结果:
1
1
说明先执行的 return
语句 x = x + 1
,再执行的finally 块。
场景三:如果 finally 块中有对返回值 x 的修改,会返回给调用者吗?
对上述代码稍做修改:
public class Test {
public static void main(String[] args) {
int back = Test.test();
System.out.println("调用者中 x = " + back);
}
public static int test() {
int x = 0;
try {
throw new Exception();
} catch (Exception e) {
return x = x + 1;
} finally {
x = x - 1;
System.out.println("finally中 x = " + x);
}
}
}
执行上述代码,结果如下:
finally中 x = 0
调用者中 x = 1
这下有点意思了,finally 块中的 x = x - 1
虽然执行了,但是并没有影响返回值。这说明在 return 那已经确定并保存了返回值,finally 块里的语句是改变了 x 的值,但并没有改变要返回的值。