pra*_*eep 0 java exception-handling exception try-catch-finally
finally当我们可以关闭文件和所有块时,需要阻止什么catch.无论我们在finally块中关闭或清除什么,都可以在块中完成catch.请告诉我,如果我错了.
无论是否抛出异常,您通常都希望执行相同的清理操作.只使用catch块这样做很痛苦 - 特别是如果你想确保你只调用close()一次,即使它会抛出.你最终得到:
bool closeCalled = false;
OutputStream stream = ...;
try {
stream.write(...);
closeCalled = true;
stream.close();
} catch (IOException e) {
if (!closeCalled) {
// TODO: Add another try/catch here? What do we want to
// do if this throws?
stream.close();
}
throw e;
}
Run Code Online (Sandbox Code Playgroud)
与之相比:
OutputStream = ...;
try {
stream.write(...);
} finally {
// TODO: Still need to work out what to do if this throws.
stream.close();
}
Run Code Online (Sandbox Code Playgroud)
或者最好的:
try (OutputStream stream = ...) {
stream.write(...);
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我认为最后一个例子是迄今为止最干净的例子 - 你真的想要到处都是第一块代码吗?哦,这是一个简单的例子 - 我们只捕获一个例外.想象一下,在每个catch子句中重复该代码,并且如果有多种方法退出该try块,则重复每个子句的关闭调用,也是...... ick.
此外,正如尼古拉斯在评论中所指出的那样,有些未经检查的例外情况是你没有抓到的(抓住和重新抛出可能会很痛苦).从根本上说,"我只是想清理我的资源,无论发生什么"的原则非常非常引人注目......