考虑到这段代码,我能绝对确定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");
}
当前回答
在正常的执行过程中考虑这一点(即不抛出任何异常):如果方法不是“void”,那么它总是显式返回一些东西,然而,最终总是执行
其他回答
考虑这一点的逻辑方法是:
放置在finally块中的代码必须在try块中执行因此,如果try块中的代码试图返回一个值或抛出一个异常,则该项将被“搁置”,直到finally块可以执行因为finally块中的代码(根据定义)具有高优先级,所以它可以返回或抛出任何它喜欢的东西。在这种情况下,“搁在架子上”的任何东西都会被丢弃。唯一的例外是,如果VM在try块期间完全关闭,例如通过“System.exit”
除非由于JVM崩溃或调用System.exit(0)而导致程序异常终止,否则finally块将始终执行。
除此之外,finally块中返回的任何值都将覆盖finally块执行之前返回的值,因此在使用try finally时,请注意检查所有退出点。
是的,因为没有控制语句可以阻止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
}
}
即使在try块中放入return语句,也始终执行finally块。finally块将在return语句之前执行。
尝试这段代码,您将了解finally块中的代码是在return语句之后执行的。
public class TestTryCatchFinally {
static int x = 0;
public static void main(String[] args){
System.out.println(f1() );
System.out.println(f2() );
}
public static int f1(){
try{
x = 1;
return x;
}finally{
x = 2;
}
}
public static int f2(){
return x;
}
}