Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

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

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>");
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs

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

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 BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly.

Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed.

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...