Home » Java Tutorial » Java try with resources

Java try with resources


Reading Time - 8 mins

Java 7 introduced a new way of closing the resources using Automatic resource management or try-with-resources. In this tutorial, we will learn in detail how to use try-with-resources.

Java try-with-resources

Java try-with-resources means declaring the resource within the try statement. A resource is nothing but closing or releasing an object after its use. This is mainly to release the memory occupied by the object. Prior to Java 7, we close the object in the finally block so that it safely releases the object if any exception occurs. Now, we can replace the finally statement with the try-with-resource statement which automatically closes the object.

We can use Automatic resource management in Java to close any resource object that implements java.lang.AutoCloseable or java.io.Closeable.

Syntax

try(resource declaration) {
  //code
}
catch(ExceptionType e) {
//handle exception
}

Example of try-with-resource

Below is an example of java try-with-resource statement to automatically close the resource. Once it executes the try block, it safely closes the object bu invoking the close method of AutoCloseable interface.

import java.io.*;

public class TryDemo {
  
  public static void main(String[] args) {
    String filename = "E\\CheckedException.txt";
    try(BufferedReader br = new BufferedReader(new FileReader(filename))) {
      System.out.println(br.readLine());
    }
    catch(IOException e) {
      System.out.println(e.getMessage());
    }

  }

}

Below is the output when there is no exception.

This is an example of checked exception

Output when an exception occurs. For example, when we pass an incorrect file name as CheckedExceptions.txt instead of CheckedException.txt, it throws FileNotFoundException.

E:\CheckedExceptions.txt (The system cannot find the file specified)

If we are not using java try-with-resources, then the code will look as below using try-catch-finally. Within the finally block, we need to close the BufferedReader object using try-catch.

import java.io.*;

public class TryDemo {
  
  public static void main(String[] args) {
    String filename = "E:\\CheckedException.txt";
    BufferedReader br = null;
    try {
      br = new BufferedReader(new FileReader(filename));
      System.out.println(br.readLine());
    }
    catch(IOException e) {
      System.out.println(e.getMessage());
    }
    finally {
      try {
        if(br != null)
          br.close();
      }
      catch(IOException e) {
        e.printStackTrace();
      }
    }

  }

}

Java try-with-resources using multiple resources

Similar to handling multiple exceptions, we can handle multiple resources using the try statement. We can specify the resources using a semicolon separator(;).

READ  Java Super Keyword

Syntax:

try(resource1;resource2) {
 //code
}
catch(Exception e) {
 //Handle exception
}

Example:

In the below example, we have used BufferedReader and BufferedWriter as 2 resources in the try statement. Using automatic resource management, it automatically closes both the resources. While closing, it closes the objects in the reverse order.

import java.io.*;

public class MultiResourceDemo {

  public static void main(String[] args) {
    String filename = "E:\\Input.txt";
    String fname = "E:\\Output.txt";
    try(BufferedReader br = new BufferedReader(new FileReader(filename));
        BufferedWriter bw = new BufferedWriter(new FileWriter(fname))){
        
      String line = br.readLine();
      System.out.println("Read from input file");
      System.out.println("Text in input file is: " + line);
      bw.write(line);
      System.out.println("Write to output file");
    }
    catch(IOException e) {
      System.out.println(e.getMessage());
    }
    catch(NullPointerException e) {
      System.out.println(e.getMessage());
    }

  }

}
Read from input file
Text in input file is: Example of try-with-resources
Write to output file

Java try-with-resources using finally

We can also use the finally block along with java try-with-resources similar to normal try-catch. The finally block executes after successfully closing all the open resources. It executes irrespective of whether an exception occurs or not.

import java.io.*;

public class TryDemo {
  
  public static void main(String[] args) {
    String filename = "C:\\Users\\nandi\\Documents\\Input.txt";
    try(BufferedReader br = new BufferedReader(new FileReader(filename))) {
      System.out.println("File Content:");
      System.out.println(br.readLine());
    }
    catch(IOException e) {
      System.out.println(e.getMessage());
    }
    finally {
      System.out.println("Finally block");
    }

  }

}
File Content:
Example of try-with-resources
Finally block

Java 9 enhanced try-with-resources

Java 9 introduced an enhanced version of try-with-resources. Instead of directly creating an instance of the resource in the try parentheses, we can declare the resource before the try block and use the object alone inside the try parentheses.

Before Java 9

try(BufferedReader br = new BufferedReader(new FileReader(filename))) {
 //code
}

After Java 9

BufferedReader br = new BufferedReader(new FileReader(filename));
try(br) {
 //code
}

Both codes handle automatic resource management.

Suppressed expressions

There are situations where both try block and the try-with-resources statements can produce an exception. In this case, the try block exception is thrown and the try-with-resources exception is suppressed.

READ  Java For-Each Loop

We can retrieve these suppressed expressions in Java 7 version and above using the Throwable.getSuppressed() method. It returns an array of exceptions and can get it in the catch block.

catch(IOException e) {
  System.out.println(e.getMessage());
  Throwable[] exceptions = e.getSuppressed();
  for(int i=0;i<exceptions.length;i++) {
    System.out.println("Suppressed exceptions: " + exceptions[i]);
  }
}

Advantages of try-with-resources

Below are the benefits and features of using java try-with-resources.

  • We do not require finally block to close the resources.
  • We can use multiple resources at the same time in the try statement.
  • It makes the code more readable and understandable.
  • It implements automatic resource management.

Implementing custom resource with AutoCloseable interface

We can create our own resource class by implementing either the AutoCloseable or Closeable interface. We need to override the method close in our own resource close. When we call the new resource within the try statement, it automatically calls the close method after try block execution.

public class ExceptionClass {

  public static void main(String[] args) {
    try(NewResource r = new NewResource()) {
      System.out.println("Calling New Resource within try block");
    }
    catch(Exception e) {
      System.out.println(e.getMessage());
    }
    System.out.println("Outside try block");
  }
  
  static class NewResource implements AutoCloseable {

    @Override
    public void close() throws Exception {
      System.out.println("Closed new resource");
      
    }
    
  }

}
Calling New Resource within try block
Closed new resource
Outside try block

 

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions