首页 > 解决方案 > 为什么finally块存在?

问题描述

在大多数编程语言中,可以在 try 或 catch 块之后放置一个 finally 块,如下所示:

try {
    sensitiveFunction();
} catch (Exception e) {
    executedWhenFailed();
} finally {
    alwaysExecuted();
}

但是我们可以在没有 finally 块的情况下执行相同的代码:

try {
    sensitiveFunction();
} catch (Exception e) {
    executedWhenFailed();
}

alwaysExecuted();

那么,为什么 finally 块存在?有人有需要 finally 块的示例吗?

谢谢

标签: try-catch-finally

解决方案


即使这些示例也不等效: if sensitiveFunction()throws something which doesn't extend Exception but Errorinstead , alwaysExecutedwill not be executed without finally(请不要试图通过 catch 来“修复”这个问题Throwable)。

或者说executedWhenFailed()自己抛出异常:catch在添加一些信息后从块中重新抛出异常是很常见的。同样,alwaysExecuted()不会在第二个片段中执行。

或者假设您有return sensitiveFunction();而不只是一个电话。等等等等。


推荐阅读