考虑到这段代码,我能绝对确定finally块总是执行的吗,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
考虑到这段代码,我能绝对确定finally块总是执行的吗,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
当前回答
添加到@vibhash的答案中,因为没有其他答案解释了在像下面这样的可变对象的情况下会发生什么。
public static void main(String[] args) {
System.out.println(test().toString());
}
public static StringBuffer test() {
StringBuffer s = new StringBuffer();
try {
s.append("sb");
return s;
} finally {
s.append("updated ");
}
}
将输出
sb已更新
其他回答
示例代码:
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("something is printed");
}
}
输出:
something is printed.
0
是的,因为没有控制语句可以阻止finally被执行。
下面是一个参考示例,其中将执行所有代码块:
| x | Current result | Code
|---|----------------|------ - - -
| | |
| | | public static int finallyTest() {
| 3 | | int x = 3;
| | | try {
| | | try {
| 4 | | x++;
| 4 | return 4 | return x;
| | | } finally {
| 3 | | x--;
| 3 | throw | throw new RuntimeException("Ahh!");
| | | }
| | | } catch (RuntimeException e) {
| 4 | return 4 | return ++x;
| | | } finally {
| 3 | | x--;
| | | }
| | | }
| | |
|---|----------------|------ - - -
| | Result: 4 |
在下面的变体中,返回x;将跳过。结果仍然是4:
public static int finallyTest() {
int x = 3;
try {
try {
x++;
if (true) throw new RuntimeException("Ahh!");
return x; // skipped
} finally {
x--;
}
} catch (RuntimeException e) {
return ++x;
} finally {
x--;
}
}
当然,引用可以跟踪其状态。此示例返回值为4的引用:
static class IntRef { public int value; }
public static IntRef finallyTest() {
IntRef x = new IntRef();
x.value = 3;
try {
return x;
} finally {
x.value++; // will be tracked even after return
}
}
除其他响应外,重要的是要指出,“finally”有权通过try重写任何异常/返回值。。捕捉块。例如,以下代码返回12:
public static int getMonthsInYear() {
try {
return 10;
}
finally {
return 12;
}
}
类似地,以下方法不会引发异常:
public static int getMonthsInYear() {
try {
throw new RuntimeException();
}
finally {
return 12;
}
}
虽然以下方法确实抛出了它:
public static int getMonthsInYear() {
try {
return 12;
}
finally {
throw new RuntimeException();
}
}
因为无论你遇到什么情况,总要进行决赛。您没有异常,它仍然被调用,捕获异常,它仍被调用
这是Java语言规范中的官方词汇。
14.20.2.执行try finally和try catch finally
带有finally块的try语句通过首先执行try块来执行。然后有一个选择:如果try块的执行正常完成,[…]如果try块的执行因抛出值V而突然完成,[…]如果由于任何其他原因R,try块的执行突然完成,则执行finally块。然后有一个选择:如果finally块正常完成,则try语句由于原因R而突然完成。如果finally块因原因S而突然完成,则try语句因原因S突然完成(并且原因R被丢弃)。
返回的规范实际上明确了这一点:
JLS 14.17退货声明
退货声明:返回表达式(opt);没有表达式的return语句试图将控制传递给包含它的方法或构造函数的调用者。带有表达式的return语句试图将控制权传递给包含它的方法的调用者;表达式的值变为方法调用的值。前面的描述说的是“试图传递控制”而不仅仅是“传递控制”,因为如果在方法或构造函数中有任何try语句,其try块包含return语句,那么在将控制传递给方法或构造函数的调用程序之前,这些try语句的任何finally子句都将按从内到外的顺序执行。finally子句的突然完成可能会中断由return语句发起的控制权转移。