JavaError HandlingIntermediate

try-with-resources

The `try-with-resources` statement automatically closes resources that implement the `AutoCloseable` interface, preventing resource leaks and simplifying cleanup code.

Review the syntaxStudy the examplesOpen the coding app
try (ResourceType resource = new ResourceType()) { /* use resource */ } catch (Exception e) { /* handle error */ }

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

The `try-with-resources` statement automatically closes resources that implement the `AutoCloseable` interface, preventing resource leaks and simplifying cleanup code.

Introduced in Java 7, the `try-with-resources` statement is a significant improvement for managing resources that need to be closed after use, such as `InputStream`, `OutputStream`, `Reader`, `Writer`, `Connection`, `Statement`, and `ResultSet`. It ensures that each resource declared in the `try` statement's parentheses is closed automatically and safely, regardless of whether the `try` block completes normally or an exception is thrown. Resources must implement the `java.lang.AutoCloseable` interface. This eliminates the need for verbose `finally` blocks with nested `try-catch` statements for closing resources, making code cleaner and less prone to resource leaks. If multiple resources are declared, they are closed in the reverse order of their declaration. Any exceptions thrown during the closing process are suppressed and can be retrieved using `Throwable.getSuppressed()`. Best practices dictate using `try-with-resources` whenever working with any `AutoCloseable` resource to guarantee proper cleanup and improve code robustness.

Quick reference

Syntax

try (ResourceType resource = new ResourceType()) { /* use resource */ } catch (Exception e) { /* handle error */ }

Inputs

Parameters

resourceAutoCloseable · One or more resources that implement `java.lang.AutoCloseable`, declared and initialized within the parentheses.

See it in practice

Examples

1

Reading a file with try-with-resources

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReadARM {
    public static void main(String[] args) {
        String filePath = "sample.txt";
        // Create a dummy file for demonstration
        try (java.io.FileWriter writer = new java.io.FileWriter(filePath)) {
            writer.write("Hello from try-with-resources!");
        } catch (IOException e) {
            System.err.println("Error creating file: " + e.getMessage());
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}
Output:
Hello from try-with-resources!

The `BufferedReader` and `FileReader` are declared within the `try` parentheses. They are automatically closed when the `try` block exits, even if an `IOException` occurs.

2

Multiple resources in try-with-resources

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

public class CopyFileARM {
    public static void main(String[] args) {
        String source = "source.txt";
        String destination = "destination.txt";

        // Create dummy source file
        try (FileOutputStream fos = new FileOutputStream(source)) {
            fos.write("Data to copy".getBytes());
        } catch (IOException e) { System.err.println("Error creating source: " + e.getMessage()); }

        try (FileInputStream in = new FileInputStream(source);
             FileOutputStream out = new FileOutputStream(destination)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            System.err.println("Error during file copy: " + e.getMessage());
        }
    }
}
Output:
File copied successfully.

Both `FileInputStream` and `FileOutputStream` are declared in the `try` statement. They will be closed automatically in reverse order of their declaration.

3

Custom AutoCloseable resource

class MyResource implements AutoCloseable {
    private String name;
    public MyResource(String name) {
        this.name = name;
        System.out.println(name + " opened.");
    }

    public void doWork() {
        System.out.println(name + " doing work.");
    }

    @Override
    public void close() throws Exception {
        System.out.println(name + " closing.");
        // Simulate an error during close
        // throw new Exception("Error during closing " + name);
    }
}

public class CustomARM {
    public static void main(String[] args) {
        try (MyResource res1 = new MyResource("Resource A");
             MyResource res2 = new MyResource("Resource B")) {
            res1.doWork();
            res2.doWork();
            // Simulate an exception in try block
            // throw new RuntimeException("Error in try block");
        } catch (Exception e) {
            System.err.println("Caught exception: " + e.getMessage());
            for (Throwable suppressed : e.getSuppressed()) {
                System.err.println("Suppressed: " + suppressed.getMessage());
            }
        }
    }
}
Output:
Resource A opened. Resource B opened. Resource A doing work. Resource B doing work. Resource B closing. Resource A closing.

Any class implementing `AutoCloseable` can be used with `try-with-resources`. The `close()` method is automatically invoked. If an exception occurs in `close()`, it becomes a suppressed exception.

Debug faster

Common Errors

1

Compile-time Error

Cause: Attempting to use a resource in `try-with-resources` that does not implement `AutoCloseable`.

Fix: Ensure the resource class implements `java.lang.AutoCloseable` (or `java.io.Closeable`, which extends `AutoCloseable`).

class NotCloseable { /* ... */ }
// Compile-time error: Incompatible types: NotCloseable cannot be converted to AutoCloseable
// try (NotCloseable res = new NotCloseable()) { /* ... */ }
2

Runtime Error (Suppressed Exception)

Cause: An exception occurs in the `try` block, and another exception occurs in the `close()` method of a resource.

Fix: The exception from the `try` block is the primary exception, and exceptions from `close()` are suppressed. Retrieve suppressed exceptions using `e.getSuppressed()` for full error reporting.

class FaultyResource implements AutoCloseable {
    @Override public void close() throws Exception { throw new Exception("Close error"); }
}
try (FaultyResource r = new FaultyResource()) {
    throw new RuntimeException("Try block error");
} catch (Exception e) {
    // e will be RuntimeException, Close error is suppressed
    // System.out.println(e.getMessage());
    // for (Throwable s : e.getSuppressed()) { System.out.println(s.getMessage()); }
}

Runtime support

Compatibility

JVMN/AJava 7+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

The `try-with-resources` statement automatically closes resources that implement the `AutoCloseable` interface, preventing resource leaks and simplifying cleanup code.

resource: One or more resources that implement `java.lang.AutoCloseable`, declared and initialized within the parentheses.

Compile-time Error: Ensure the resource class implements `java.lang.AutoCloseable` (or `java.io.Closeable`, which extends `AutoCloseable`). Runtime Error (Suppressed Exception): The exception from the `try` block is the primary exception, and exceptions from `close()` are suppressed. Retrieve suppressed exceptions using `e.getSuppressed()` for full error reporting.