In this article, we are going to discuss about the improvement made in ‘Try-With-Resources’ feature in the Java 9 Release. But, in order to understand the change being made, we need to know first what actually ‘try-with-resources’ feature is. So, let’s go ahead and learn all of that in this post with examples.


Check out: Iterate / ofNullable operations in Java 9 Stream

Try-With-Resources Improvement in Java 9...!!! Click To Tweet

In this article, we are going to cover below points:

  1. What is ‘Try-With-Resources’ feature in Java 7?
  2. Limitation with this feature in Java 7?
  3. How Java 9 solves that problem?

Let’s begin:

1. What is ‘Try-with-Resource’ feature in Java 7?

Try-with-Resource was introduced in Java 7 and it’s purpose is to close the resource(s) automatically after being used. Let’s say you are using any object implementing java.lang.AutoCloseable or interface like File object OR Database object . Now, the objective was to close such resources once their usage is done. Before Java 7, you had to explicitly close such objects in the finally block. But, Java 7 helps to auto-close such resources once used.

Great Huh….

2. Is there any limitation with this feature in Java 7, if yes, what is it?

Yes. There is a limitation here. Challenge is that the resource need to be declared before try or inside the try statement else it will throw the compilation error. See examples below:

Below code will work in Java 7: (because object is declared within try statement)

Below code won’t work in Java 7: (because object is not declared within try statement)

Java 7 Error message:

3.  How Java 9 handle this limitation?

Well, Java 9 improved ‘Try-With-Resources’ and it is no longer needed to declare the object inside the try statement. Lets run the above  example( in Java 9 now.

It will work completely fine and will generate the below output.

Java 9 Output:

Try-With-Resources Improvement in Java 9...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References:


  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.