Wednesday, April 6, 2011

try with resource block

Often we use the try block while using resources like Streams and Connections. In these cases it is mandatory to close the resources after the completion of the task. We usually do the same in the finally block as in the example below

BufferedReader br = new BufferedReader(new FileReader(path));

try {

return br.readLine();

} finally {

br.close();

}

In Java 7 this process has been shortened by the try-with-resource statement. In this the resources are implicitly closed on the completion of the try fragment irrespective of whether the code was successfully executed or with exception. The only change is that the resource must implement the java.lang.AutoCloseable interface. The classes java.io.InputStream, OutputStream, Reader, Writer, java.sql.Connection, Statement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.

The Catch Blocks

Java 7.0 has come up with a new feature where it is possible to catch multiple exceptions in a particular catch block. For example

catch (IOException | SQLException ex) {

logger.log(ex);

throw ex;

}

In this case both IOException and SQLException will be caught in the same block.It has to be noted though that the parameter is implicitly final i.e the parameter cannot be assigned to any other Object.