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>");
}
}
As explained above this is a feature in Java 7 and beyond.
try with resources
allows to skip writing thefinally
and closes all the resources being used intry-block
itself. As stated in DocsSee this code example
In this example the resource is
BufferReader
object as the class implements the interfacejava.lang.AutoCloseable
and it will be closed whether the try block executes successfully or not which means that you won't have to writebr.close()
explicitly.Another important thing to notice here is that if you are writing the
finally
block yourself and both yourtry
andfinally
block throw exception then the exception fromtry
block is supressed.While on the other hand if you are using
try-with-resources
statement and exception is thrown by bothtry
block andtry-with-resources
statement then in this case the exception fromtry-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
This is a new feature in Java 7 and beyond. Without this, you'd need a
finally
block which closes the resourcePrintWriter out
. So the code above is equivalent to:See The try-with-resources Statement