Java try with resources statement

Java Exception handling try with resources statement.

Similar to Multi-catch introduced in Java 7 another enhancement made is the try-with-resources Statement.

Earlier the resources need to be close inside the try{ …. } block. But since Java 7 this can be using try-with-resources Statement.

As per the oracle doc

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 java.io.Closeable, can be used as a resource.

See the below code snippet before Java 7.

public class TryWithResourceExample {

    public static void main(String[] args) {
        readFile("/home/input.txt");
    }

    static String readFile(String path) {
        File file = null;
        try {
            StringBuilder sb = new StringBuilder();
            file = new File(path);
            Scanner sc = new Scanner(file);
            while(sc.hasNextLine()) {
                
                sb.append(sc.nextLine());
            }
            sc.close();
            
            return sb.toString();
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

The above code can be rewritten using the try with a resource statement like the below.

public class TryWithResourceExample {

    public static void main(String[] args) {
        readFile("/home/input.txt");
    }

    static String readFile(String path) {
        StringBuilder sb = new StringBuilder();
        
        try (Scanner sc = new Scanner(new File(path))){
            
            while(sc.hasNextLine()) {
                sb.append(sc.nextLine());
            }
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

The try with the resource can also be used with multiple closeable resources. Observe the following code snippet.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TryWithResourceExample {

    public static void main(String[] args) {
        readFile("/home/inputfile.txt");
    }

    static void readFile(String path) {
        
        try (InputStream i = new FileInputStream(new File(path)); 
             BufferedReader reader = new BufferedReader(new InputStreamReader(i));    
            ){
            
            System.out.println("File content is : "+reader.readLine());
            
        }catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}

Point to remember: Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used inside the try with resource statement.

For Objects that do not implement AutoCloseable, the compiler will alert the following error.

The resource type {Resource name} does not implement java.lang.AutoCloseable

Recommended read:

Java Exception in detail with example
How to create custom Java Exception?

Happy Learning !!

Leave a Comment