Java - Try vs Try-with-Resources

JDK 7 comes with try-with-resources feature which allows automatic closing of resources without explicit finally block leading to minimal code and avoids boilerplate code required for closing of resources.

pre-JDK 7

 JDK 7 onwards

Compare both the implementations with Examples :

Lets see the examples of both normat try statement and try-with-resources statement.

pre-JDK 7 ( nomral Try statement ) Example

 JDK 7 onwards ( try-with-resources statement ) Example

Resource - Any class which implements AutoCloseable interface. Java 7 onwards, most of the classes including BufferedReader, BufferedWriter etc, implements AutoCloseable .

Custom Resource implementation Example :

Lets now implement some resource which can be used in try-with-resources statement.

Now use the resource in try-with-resource statement.


MyCustomResource is created and doing some work
MyCustomResource is closed
Exception from try block statement doSomeWork() : doSomeWork exception
Exception from resource close() : close exception

Here, you can understand the flow of execution by looking at output statements above.

Some points to be noted :
1) Always , resources would be closed immediately after the try block and before catch/finally.
2) Try block exception can be accessed directly through exception object whereas resource closing exception would be suppressed and need to be accessed through the method getSuppressed().




Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">