Try with Resources Example

Try with Resources Example


Every version of Java adds some new features and the latest version JDK 1.7 (as on August, 2013) comes with new additions.

Following are the new additions.

1. String in Switch Expression
2. Underscores Between Digits in Numeric Literals
3. Integral Types as Binary Literals
4. Handling multiple exceptions in a single catch block
5. Try-with-resources Statement
6. Automatic Type Inference in Generic object instantiation

Now let us discuss Try with Resources Example Statement

With JDK 1.7, no finally block is required to close (with close() methods) the resources of files or sockets or JDBC handles (objects) etc. The resources (say objects) opened in try block automatically close when the execution control passes out try block (say, at the close brace of try block).

Your Earlier code before Java 7:

Your Present code with JDK 1.7:

A new interface AutoCloseable is introduced with JDK 1.7 for this purpose.

Any resource (class) that implements interface "java.lang.AutoCloseable" is eligible as a resource statement to write in try block.

The close() method of AutoCloseable is called implicitly to close the handles. Observe, the close() method throws Exception which you may or may not catch if your code does not demand, or replace with problem specific exception class. In the above code, I used IOException. Note that close() method java.lang.Closeable interface is very different from this.

JDBC 4.1 can make use of this try-catch-resource management.

All the remaining features (including the present one) are discussed in JDK 1.7 Features.

Leave a Reply

Your email address will not be published. Required fields are marked *