The Try with Resources Statement

The try-with-resources statement is an expanded form of the try statement that enables Automatic Resource Management (ARM) in Java. This form of the try statement provides an efficient exception handling mechanism that automatically closes resources after they are used. The try-with-resources statement is available only in JDK 7 and higher versions of Java.

How Try with Resources Works

The term resource refers to any object such as a file or a stream that must be closed after use. It is important to close every resource after the program finishes working on it. Closing a resource ensures that the resource is released and made available to other programs.

Prior to JDK 7, every resource used in a program had to be closed explicitly using the close() method. When the try with resources statement is used, the close() statement is not required to close resources. The try with resources statement makes it easier to manage resources by ensuring that all resources used within the try block are automatically closed after use.

Syntax

try(resource-specification){

//code block that uses the resource

}

In the resource-specification statement, a variable is declared and initialized with a reference to the required resource. When the try block completes execution, the specified resource is automatically closed and released. You can also include the catch and finally blocks with the try-with-resources statement.

Key Points for Try with Resources

The following are key points to be noted while using the try with resources statement:

  • A resource specified in the try with resources statement must be an object of a class that implements the AutoCloseable interface. The close() method is available in the AutoCloseable interface.

The AutoCloseable interface is defined by java.lang. It is inherited by the Closeable interface available in java.io.
  • The try with resources statement can include one or more resource specifications separated by semicolons. When the try block completes execution, all the specified resources are closed.

  • The resources declared in the try with resources statement are available as local variables within the try block. This means that the scope of these resources is limited to the try with resources statement only.

  • The resources declared in the try with resources statement are final. It is not possible to assign to these resources after their creation.

  • A try-with-resources statement can generate suppressed expressions.

Example

The following program illustrates the use of try-with-resources statement to copy one file to another:

MinimumAccountBalance.java
package onlinetutorialspoint;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TryWithExample {

    public static void main(String args[]) throws IOException {
        int n;
        if (args.length != 2) {
            System.out.println("Specify two file names: TryWithExample from to");
            return;
        }

        try (FileInputStream fin = new FileInputStream(args[0]);
             FileOutputStream fout = new FileOutputStream(args[1])) {
            do {
                n = fin.read();
                if (n != -1) {
                    fout.write(n);
                }
            } while (n != -1);
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        }
    }
}

In this program, the try-with-resources statement uses two variables, fin, which refers to the input file, and fout, which refers to the output file. After the input file is copied to the output file in the do…while loop, the try block ends and the two files are automatically closed.

To execute this program you need to provide two file names.

For example, TryWithExample Test1.txt Test2.txt

Suppressed Exceptions

In older Java code, the close() method is usually called in the finally block to close resources. Suppose the try block throws an exception. Irrespective of any exception, the finally block gets executed and the close() method closes the resource. It is possible that the close() method also throws an exception. When this happens, the exception thrown by the close() method takes precedence and the first exception thrown by the try block is lost.

The try with resources statement provides a way to handle all exceptions in the order in which they are thrown. If a try-with-resources statement is used instead of the try statement in the previous example, the exception thrown in the finally block is suppressed. This exception is added to a list of suppressed exceptions that are associated with the first exception.

The getSuppressed() method in the Throwable class can be used to retrieve the list of suppressed exceptions.

Advantages of try with resources :

Some of the advantages of using the try-with-resources statement include:

  • Automatic release of resources: Automatic closure of resources prevents situations where a file is inadvertently locked or a resource is not released by a program.

  • Easier to maintain code: The use of try-with-resources statement results in streamlined source code that is easier to understand and maintain.

  • Effective resource management: All the resources needed within the try block are initialized and closed correctly. This ensures that resources are managed effectively and prevents memory leaks.

Happy Learning 🙂