69

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

}
Jim Fell
  • 13,750
  • 36
  • 127
  • 202
Umair Hashmi
  • 711
  • 1
  • 5
  • 8

2 Answers2

84

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

zb226
  • 9,586
  • 6
  • 49
  • 79
Syed Ali Taqi
  • 4,898
  • 3
  • 34
  • 44
  • 4
    So it's analogous to C#'s using & IDisposable 's. – roufamatic Oct 25 '16 at 17:26
  • 2
    @roufamatic yes, analogous, though the large difference is that C#'s `using` does not protect in any way against exceptions, it just guarantees resource closure at the end of the block. In C#, you most often have to combine `using` blocks with `try` blocks. Java's `try-with-resources` does this together. – Michael Plautz Apr 27 '18 at 04:26
  • If an exception is thrown from both the `try-with-resources` statement and the `try-with-resources` block, only the `try-with-resources` statement exception would be encountered (would not be suppressed) because the `try-with-resources` block wouldn't have an opportunity to execute. – dan Mar 09 '23 at 14:18
13

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

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

See The try-with-resources Statement

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 2
    They are not equivalent. If the exception throws from both try and finally blocks, the exception from try block will be suppressed with try-and-catch. On the other hand, if you use the try-with-resources statement, the exception from finally block (auto close throws exception) will be suppressed. – Nier Dec 21 '17 at 09:30
  • @Nier Fixed the finally part. – Aaron Digulla Dec 30 '17 at 10:27