Java 为什么要在没有 Catch 或 finally 的情况下编写 Try-With-Resources?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26356777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:20:16  来源:igfitidea点击:

Why write Try-With-Resources without Catch or Finally?

javatry-with-resources

提问by Umair Hashmi

Why write Try without a Catch or Finally as in the following example?

为什么编写 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>");
    }

}

采纳答案by Syed Ali Taqi

As explained above this is a feature in Java 7 and beyond. try with resourcesallows to skip writing the finallyand closes all the resources being used in try-blockitself. As stated in Docs

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

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

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

See this code example

请参阅此代码示例

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

In this example the resource is BufferReaderobject as the class implements the interface java.lang.AutoCloseableand it will be closed whether the try block executes successfully or not which means that you won't have to write br.close()explicitly.

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

Another important thing to notice hereis that if you are writing the finallyblock yourself and both your tryand finallyblock throw exception then the exception from tryblock is supressed.

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

While on the other hand if you are using try-with-resourcesstatement and exception is thrown by both tryblock and try-with-resourcesstatement then in this case the exception from try-with-resourcesstatement is suppressed.

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

As the @Aaron has answered already above I just tried to explain you. Hope it helps.

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

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

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

回答by Aaron Digulla

This is a new feature in Java 7 and beyond. Without this, you'd need a finallyblock which closes the resource PrintWriter out. So the code above is equivalent to:

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

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

See The try-with-resources Statement

请参阅try-with-resources 声明