Home » Java programming language

The try-with-resource statement in Java

In this tutorial, we will learn to use the try-with-resource statement/block to handle exceptions. This section/block helps us to close resources automatically without having to explicitly close them in catch block or finally block.
Submitted by Saranjay Kumar, on March 01, 2020

Consider the following function:

import java.io.*;

public class Try {
    public static void main(String args[]) {
        Try ob = new Try();
        ob.func();
    }

    void func() {
        BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"));

        try {
            System.out.println(br.readLine());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}

In this case, we utilize a resource of BufferedReader class. If the method br.readLine() throws an exception (or even in the case it doesn't throw an exception), the resource of BufferedReader class remains open. In Java, it is very essential to close all resources when they are no longer needed. One way to implement it is to make use of final block, where we close the necessary resources.

import java.io.*;

public class Try {
    public static void main(String args[]) {
        Try ob = new Try();
        ob.func();
    }

    void func() {
        BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"));

        try {
            System.out.println(br.readLine());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (br != null) br.close();
        }

    }

}

In case we establish a connection to many resources in the try block, we would need to close all of them one by one in the finally block. Another method, which is supported by Java 7 and all later versions, is to use a try-with-resource block.

The general syntax of the try-with-resource block is:

try (  //Open Resources here  )
{
  //Use Resources here
}
catch( //Catch exceptions here  )
{
//Handle Exceptions here
}
//Resources get automatically closed

In the try-with-resource block, all resources get automatically closed. We can have caught and finally blocks along with the try-with-resource block. Any catch or finally block is run after the resources have been closed. We can open multiple resources in the try-with-resource statement, all of which must implement the Java.lang.AutoCloseable interface. The resources are closed in the reverse order in which they were created.

Consider the following update to our code:

import java.io.*;

public class Try {
    public static void main(String args[]) {
        Try ob = new Try();
        ob.func();
    }

    void func() {
        try (BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"))) {
            System.out.println(br.readLine());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

C:\example.txt (No such file or directory)

The BufferedReader resource is automatically closed whether the try block executes normally or abruptly.

The try-with-resource has several advantages:

  • It makes the code easier to read and interpret
  • Resources are managed automatically
  • We don't need to make a finally block especially to close the resources
  • Multiple resources can be opened in the try-with-resource statement, separated by semicolons
  • Resources are closed in the reverse order to avoid any dependency issues
import java.io.*;

public class Try {
    public static void main(String args[]) {
        Try ob = new Try();
        ob.func();
    }

    void func() {
        try (FileInputStream fin = new FileInputStream("file.txt"); BufferedReader br = new BufferedReader(new FileReader("C:\\example.txt"))) {
            System.out.println(br.readLine());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

file.txt (No such file or directory)

Note: The outputs in these programs throw an exception because they refer to files that are not present at that path.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.