Java Try-with-Resources

Java try-with-resources is a try statement that automatically closes resources when the block finishes. It is commonly used with files, scanners, streams, and readers that need cleanup after use.

A resource is any object that implements AutoCloseable, which means it has a close() method Java can call for you.

Basic Syntax

Put the resource declaration inside parentheses after try. Java closes that resource after the try block finishes, even if an exception happens.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String data = "Java resources";

        try (Scanner scanner = new Scanner(data)) {
            String first = scanner.next();
            String second = scanner.next();
            System.out.println(first);
            System.out.println(second);
        }
    }
}

Output:

Java
resources

The Scanner is declared in the try parentheses, so it is the resource. When the block ends, Java automatically calls scanner.close().

Why Use It?

Before try-with-resources, cleanup was often written in a finally block. That works, but it can make code longer and easier to get wrong. Try-with-resources keeps the cleanup rule close to the resource declaration.

This is especially useful for file and stream code because open resources can hold operating system handles. Closing them promptly is a good habit.

Handling Exceptions

You can still add a catch block after try-with-resources. The resource is closed before control moves past the statement.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) {
        String text = "red\ngreen\nblue";

        try (BufferedReader reader = new BufferedReader(new StringReader(text))) {
            System.out.println(reader.readLine());
            System.out.println(reader.readLine());
        } catch (IOException e) {
            System.out.println("Could not read text.");
        }
    }
}

Output:

red
green

BufferedReader.readLine() can throw an IOException, so this example includes a catch block. The reader is still closed automatically after the try block.

Multiple Resources

A try-with-resources statement can manage more than one resource. Separate the declarations with semicolons.

class DemoResource implements AutoCloseable {
    private String name;

    public DemoResource(String name) {
        this.name = name;
        System.out.println("Open " + name);
    }

    public void use() {
        System.out.println("Use " + name);
    }

    @Override
    public void close() {
        System.out.println("Close " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        try (DemoResource first = new DemoResource("first");
             DemoResource second = new DemoResource("second")) {
            first.use();
            second.use();
        }
    }
}

Output:

Open first
Open second
Use first
Use second
Close second
Close first

Notice the closing order: resources are closed in the reverse order from how they were opened. This helps when one resource depends on another.

Good Habits

  • Use try-with-resources for objects that implement AutoCloseable, such as Scanner, BufferedReader, and many file or stream classes.
  • Keep the try block focused on the work that needs the resource.
  • Add catch blocks when you can handle a specific exception clearly.
  • Do not manually close a resource that try-with-resources is already managing.

Takeaway: try-with-resources is the preferred way to write Java cleanup code for closeable resources because it is shorter, clearer, and less error-prone than manual closing.