最后有时候会让我困惑

Mil*_*ita 21 java exception-handling exception finally try-catch

今天在大学时我们谈了一些try,catch并且finally.我对这两个例子感到困惑:

PrintWriter out = null;
try {
  out = new PrintWriter(...); // We open file here
} catch (Exception e) {
  e.printStackTrace();
} finally { // And we close it here
  out.close();
}
Run Code Online (Sandbox Code Playgroud)

关闭文件finally和我们只是这样做有什么区别:

PrintWriter out = null;
try {
  out = new PrintWriter(...); // We open file here
} catch (Exception e) {
  e.printStackTrace();
}
out.close();
Run Code Online (Sandbox Code Playgroud)

catch之后的这段代码将始终执行.

你能给我一些很好的例子来说明我们何时使用finally以及何时将代码放入catch之后的差异?我知道最终将永远执行,但程序也会在catch块之后继续运行.

Zby*_*000 33

如果代码抛出,它仍然会有所不同Error.这不会在代码中捕获,因此任何后续部分try/catch/finally都不会被捕获.如果它是它的一部分finally,它仍然会被执行Error.

其次,如果由于某种原因e.printStackTrace()抛出异常(虽然它会非常罕见),同样会发生 - finally将仍然执行.

一般来说finally,无论发生什么,都是非常安全的释放资源的方式.自Java 7以来,支持资源的尝试更加安全,因为它可以轻松管理在关闭操作期间抛出的多个异常.在这个例子中,它看起来像:

try (PrintWriter out = new PrintWriter(...)) {
    // do whatever with out
}
catch (Exception e) {
    e.print... (whatever)
}
// no need to do anything else, close is invoked automatically by try block
Run Code Online (Sandbox Code Playgroud)

编辑:还要注意你的代码不是真的正确(无论哪个版本).如果PrintWriter构造函数抛出异常,则该行将out.close()失败NullPointerException.

  • @MiljanRakita错误可能发生在任何地方.它的乐趣之一! (15认同)
  • 请记住,`finally`将*不会在真正的灾难性情况下执行(例如,电源故障),所以不要指望它维护数据库事务的一致性. (2认同)