Wednesday, 3 January 2018

Core java | try with resource Statement in Java

In Java 6, we open a file in a try block and close the file in the finally block

try {
      //open file or resources
catch(IOException) {
      //handle exception
finally {
      //close file or resources

1. You'd have to check if your resource is null before closing it.
2. The closing itself can throw exceptions so finally had to contain another try – catch.
3. Programmers tend to forget to close their resources.

In JDK 7, a new “try-with-resources” approach is introduced.
When a try block is an end, it will close or release your opened file automatically.

try(open file or resource here) {
//after try block, file will close automatically.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it.

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement, can be used as a resource.

import java.util.Scanner;

class Demo {
     public static void main(String[] args) {

           try(Scanner scan=new Scanner( {
                String str =;

Benefits of using try with resources
1. Automatic resource management.
2. More readable code and the number of lines of code is reduced.
3. No need to have finally block just to close the resources.
4. We can open multiple resources in try-with-resources statement separated by a semicolon.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));   
     Scanner scan = newScanner( {

catch (IOException e) {

5. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue.

Note for Point#5

We can extend the resource program to prove that.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...