【问题标题】:Why write Try-With-Resources without Catch or Finally?为什么要在没有 Catch 或 finally 的情况下编写 Try-With-Resources?
【发布时间】:2014-12-09 00:12:51
【问题描述】:

为什么要像下面的例子那样写 Try without a Catch 或 finally?

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet tryse</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet tryse at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }

}

【问题讨论】:

  • 阅读资源尝试(Java 7)
  • 重复“在没有“catch”的情况下进行“try-finally”是否有意义?”
  • @Juru:这绝不是那个的复制品......
  • 话虽如此,我不认为这是关于 try-with-resources 的第一个问题。不过,+1 仅仅是因为我以前从未听说过此功能!

标签: java try-with-resources


【解决方案1】:

如上所述,这是 Java 7 及更高版本中的一个特性。 try with resources 允许跳过写入finally 并关闭try-block 本身正在使用的所有资源。如Docs中所述

任何实现 java.lang.AutoCloseable 的对象,包括所有实现 java.io.Closeable 的对象,都可以用作资源。

查看此代码示例

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

在本例中,资源是BufferReader 对象,因为该类实现了接口java.lang.AutoCloseable,无论try 块是否成功执行,它都会关闭,这意味着您不必显式编写br.close()

这里要注意的另一件重要的事情是,如果您自己编写 finally 块并且您的 tryfinally 块都抛出异常,那么来自 try 块的异常是被压制了。

另一方面,如果您使用try-with-resources 语句并且try 块和try-with-resources 语句都抛出异常,那么在这种情况下,来自try-with-resources 语句的异常将被抑制。

正如@Aaron 上面已经回答的那样,我只是想向您解释一下。希望对您有所帮助。

来源:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

【讨论】:

  • 所以它类似于 C# 使用 & IDisposable 的。
  • @roufamatic 是的,类似,虽然最大的区别在于 C# 的 using 不以任何方式防止异常,它只是保证在块末尾的资源关闭。在 C# 中,您通常必须将 using 块与 try 块组合在一起。 Java 的 try-with-resources 一起完成了这项工作。
【解决方案2】:

这是 Java 7 及更高版本中的一项新功能。没有这个,你需要一个finally 块来关闭资源PrintWriter out。所以上面的代码等价于:

PrintWriter out = null;
try {
    PrintWriter out = ...
} finally {
    if(null != out) {
        try {
            out.close();
        } catch(Exception e) {} // silently ignore!
    }
}

The try-with-resources Statement

【讨论】:

  • 它们不是等价的。如果 try 和 finally 块都抛出异常,则 try 块中的异常将被 try-and-catch 抑制。另一方面,如果你使用 try-with-resources 语句,来自 finally 块的异常(自动关闭抛出异常)将被抑制。
  • @Nier 修复了 finally 部分。
猜你喜欢
  • 1970-01-01
  • 2011-02-06
  • 2012-12-24
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 2014-12-18
相关资源
最近更新 更多