try-catch-finally - 为什么finally块存在?
问题描述
在大多数编程语言中,可以在 try 或 catch 块之后放置一个 finally 块,如下所示:
try {
sensitiveFunction();
} catch (Exception e) {
executedWhenFailed();
} finally {
alwaysExecuted();
}
但是我们可以在没有 finally 块的情况下执行相同的代码:
try {
sensitiveFunction();
} catch (Exception e) {
executedWhenFailed();
}
alwaysExecuted();
那么,为什么 finally 块存在?有人有需要 finally 块的示例吗?
谢谢
解决方案
即使这些示例也不等效: if sensitiveFunction()
throws something which doesn't extend Exception
but Error
instead , alwaysExecuted
will not be executed without finally
(请不要试图通过 catch 来“修复”这个问题Throwable
)。
或者说executedWhenFailed()
自己抛出异常:catch
在添加一些信息后从块中重新抛出异常是很常见的。同样,alwaysExecuted()
不会在第二个片段中执行。
或者假设您有return sensitiveFunction();
而不只是一个电话。等等等等。
推荐阅读
- html - 如有必要,定位绝对全宽
- spring-security - 覆盖 Spring Boot 安全性
- sql - 查询运行缓慢且缺少索引
- react-native - 使用 expo 在 react-native 中重新渲染错误太多
- javascript - React Js:如何读取 csv 文件?(所有列中只有 4 列)
- html - 弯曲一个指向 div 的点
- git - 如何 git 克隆从多个 svn 项目构建的单个 svn 项目
- rust - Rust 反向指针
- encryption - FSM 问题 vhdl AES 加密未进入第三状态?
- python - 使用 Python 获取页面加载时间