考虑到这段代码,我能绝对确定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");
}

当前回答

即使在try块中放入return语句,也始终执行finally块。finally块将在return语句之前执行。

其他回答

除非由于JVM崩溃或调用System.exit(0)而导致程序异常终止,否则finally块将始终执行。

除此之外,finally块中返回的任何值都将覆盖finally块执行之前返回的值,因此在使用try finally时,请注意检查所有退出点。

我很晚才回答,但我很惊讶没有人提到Java调试器选项来删除堆栈帧。我是IntelliJ中此功能的重度用户。(我确信Eclipse和NetBeans支持相同的功能。)

如果我从后面跟着finally块的try或catch块中删除堆栈帧,IDE将提示我:“我要执行finally块吗?”显然,这是一个人工运行时环境——调试器!

为了回答您的问题,我想说,只有在连接调试器时忽略,并且(就像其他人所说的)method something()不(a)通过JNI调用Java方法System.exit(int)或(b)C函数exit(int/abort(),或(C)对自身执行类似于调用kill-9$PID(!)的疯狂操作时,才能保证它运行。

无论异常处理与否,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
    }
}

是的,总是执行finally块。大多数开发人员使用此块来关闭数据库连接、resultset对象、语句对象,还使用到java休眠来回滚事务。