Try-with-Resources: Automatic Resource Management in Java

Learn Java try-with-resources for closing AutoCloseable objects during normal control flow, with examples of close order and suppressed exceptions.

published: reading time: 14 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java try-with-resources for closing AutoCloseable objects during normal control flow, with examples of close order and suppressed exceptions.

Java 7 introduced try-with-resources for objects that implement AutoCloseable. When Java control flow leaves the block, the runtime attempts to close each initialized, non-null resource. A JVM exit, VM failure, or forced process termination can stop execution before cleanup runs.

Introduction

Before try-with-resources, code commonly used finally blocks to close files, connections, and streams. That code needed null checks and exception handling, and a failure in close() could replace an exception from the try block.

Try-with-resources addresses that exception-handling problem during ordinary Java control flow. If the body throws and close() also throws, the body exception remains primary and the close failure is attached as suppressed. If the body completes normally and close() throws, the close failure is thrown. See the JLS rules for try-with-resources and Throwable.getSuppressed().

Declare resources in the try header, for example try (BufferedReader reader = Files.newBufferedReader(path)). Initialized, non-null resources are closed in reverse declaration order when Java control flow leaves the block, including after a return or exception. This cleanup cannot run after the JVM or process has stopped; the Runtime API documents how exit() and halt() terminate the VM. For Java 9 and later, an existing final or effectively final variable can also appear in the resource list; Oracle’s Java 9 language updates describe that form.

Resources are listed together in the header, and the declaration order makes their close order visible. For most AutoCloseable resources, this is simpler and safer than manual finally cleanup.

This guide covers declaration syntax, close order, and what happens when the body and close() both throw.

When to Use

Use try-with-resources when:

  • Opening files, streams, readers, or writers
  • Acquiring database connections or network sockets
  • Working with any object implementing AutoCloseable
  • You want Java to attempt cleanup when normal or abrupt Java control flow leaves the block
// Before Java 7: verbose, error-prone
Scanner scanner = null;
try {
    scanner = new Scanner(new File("data.txt"));
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
} finally {
    if (scanner != null) {
        scanner.close();
    }
}

// Java 7+: cleanup is attempted when Java control flow leaves the block
try (Scanner scanner = new Scanner(new File("data.txt"))) {
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
}

Existing resource variables (Java 9+)

Since Java 9, the resource list can reference an existing final or effectively final variable. Do not reassign it:

void printFirstLine(Path path) throws IOException {
    BufferedReader reader = Files.newBufferedReader(path);
    try (reader) {
        System.out.println(reader.readLine());
    }
}

The declaration form shown earlier works in Java 7 and later.

When NOT to Use

  • Do not use for non-AutoCloseable resources — The declared or referenced resource must implement AutoCloseable
  • Do not mix manual and automatic cleanup — Never call close() on a resource declared in the try-with-resources header
  • Handle optional resources deliberately — A null resource is skipped; use a separate branch if the resource is optional
  • Keep non-resource cleanup separate — Use finally for cleanup that is not represented by an AutoCloseable resource

AutoCloseable Interface

classDiagram
    class AutoCloseable {
        <<interface>>
        +void close() throws Exception
    }
    class Closeable {
        <<interface>>
        +void close() throws IOException
    }
    class Connection {
        <<interface>>
        +void close() throws SQLException
    }
    class Scanner {
        +void close()
    }
    class FileInputStream {
        +void close() throws IOException
    }

    AutoCloseable <|-- Closeable
    AutoCloseable <|-- Connection
    AutoCloseable <|-- Scanner
    AutoCloseable <|-- FileInputStream
    Closeable <|-- FileInputStream

Detailed Behavior

Multiple Resources

Declaring multiple resources in one try-with-resources statement closes them in reverse declaration order. Declare a dependency first and the resource that uses it later, so the dependent closes before its dependency.

For example, a JDBC result set depends on its statement, and the statement depends on its connection:

try (Connection connection = dataSource.getConnection();
     PreparedStatement statement = connection.prepareStatement("SELECT id FROM users");
     ResultSet results = statement.executeQuery()) {
    while (results.next()) {
        System.out.println(results.getLong("id"));
    }
}

Java closes results, then statement, then connection. If a wrapper itself owns and closes its underlying stream, declare only the wrapper unless the underlying resource also has a separate lifecycle.

If the body has already thrown, close failures are added to that primary exception’s suppressed list. If the body completed normally and several resources fail to close, the first close failure is thrown and later close failures are suppressed on it. Inspect getSuppressed() to see them.

try (
    FileInputStream fis = new FileInputStream("input.txt");
    FileOutputStream fos = new FileOutputStream("output.txt")
) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        fos.write(buffer, 0, bytesRead);
    }
} // The output stream closes before the input stream.

Exception ordering

An exception can come from the try body or from close() during cleanup. If the body has already thrown, that exception remains primary and later close failures are suppressed on it.

When close() throws but the try block succeeds:

try (Resource1 r1 = new Resource1()) {
    r1.process();  // succeeds, returns normally
} // close() throws — this exception propagates directly

When the try block completes normally and close() throws, there is no primary exception to suppress. The close() exception propagates as the primary exception. Callers see the cleanup failure directly.

When the try block throws but close() succeeds:

try (Resource1 r1 = new Resource1()) {
    r1.process();  // throws RuntimeException
} // close() succeeds — primary exception propagates normally

When the try block throws and close() succeeds, the primary exception propagates normally. No suppressed exception machinery is involved.

When both the try block and close() throw:

try (Resource1 r1 = new Resource1()) {
    r1.process();  // throws RuntimeException "primary"
} // close() throws — "close failed" added as suppressed

This is the most interesting case. When both the try block and close() throw, the try block exception is the primary exception and propagates. The close() exception is added as a suppressed exception via addSuppressed(). Callers see the primary exception and can retrieve the cleanup failure via getSuppressed().

The suppressed exception mechanism was introduced specifically for this scenario. Before Java 7, a finally block throwing an exception would silently overwrite the original exception from the try block — the real cause of failure was lost. try-with-resources preserves both by tagging the cleanup exception as suppressed.

import java.io.Closeable;
import java.io.IOException;

try (Closeable resource = () -> {
    throw new IOException("close failed");
}) {
    throw new IOException("body failed");
} catch (IOException e) {
    System.out.println("Primary: " + e.getMessage());
    for (Throwable suppressed : e.getSuppressed()) {
        System.out.println("Suppressed: " + suppressed.getMessage());
    }
}

// Output:
// Primary: body failed
// Suppressed: close failed

Failure Scenarios

// Scenario 1: Resource initialization fails
try (AutoCloseable r = createResource()) {
    // If createResource() throws, resource never opened
} catch (Exception e) {
    // Handle
}

// Scenario 2: Variable not effectively final
String path = getPath();
path = "different";  // Modifying makes it unusable in try-with-resources

// Scenario 3: close() throws during normal execution
try (Resource r = new Resource()) {
    r.process();  // Throws RuntimeException
} catch (RuntimeException e) {
    // If close() also throws, suppressed exception added
    Throwable[] suppressed = e.getSuppressed();
}

Trade-off Table

Approach Pros Cons
try-with-resources Concise close attempts during Java control flow Only for AutoCloseable
try-finally Universal Verbose, easy to miss cleanup
manual try-catch Full control Easy to leak resources
null check + close Compatible with older patterns Boilerplate, error-prone

Observability Checklist

  • All I/O resources declared in try-with-resources header
  • No manual close() calls on managed resources
  • Suppressed exceptions handled in catch blocks (getSuppressed())
  • Resources properly implement AutoCloseable
  • Close failures are reported or propagated at the appropriate boundary

Security Notes

  • close() may throw — Decide how the caller should report or propagate close failures
  • Sensitive data in buffers — File and network buffers may contain sensitive data; ensure cleanup
  • Timing attacks — Resource cleanup timing can leak information about operations; use constant-time patterns when relevant
  • Do not store resources in static fields — This defeats garbage collection and cleanup
// SECURE: Handle suppressed exceptions
try (SecureResource r = new SecureResource(password)) {
    r.process();
} catch (Exception e) {
    logger.error("Resource operation failed", e);
    // Check for suppressed close() exceptions
    for (Throwable suppressed : e.getSuppressed()) {
        logger.warn("Cleanup exception: {}", suppressed.getMessage());
    }
}

Common Pitfalls

  1. Forgetting to declare resources in the header — Objects created in the body are not automatically closed unless another declared resource owns them
  2. Modifying resource variables — The variable must be effectively final to use in try-with-resources
  3. Assuming close() never throws — It can, and suppressed exceptions are easy to miss
  4. Closing resources out of order — While reverse-order closing is correct, interleaved resources can cause confusion
  5. Not checking for suppressed exceptions — Silent close() failures lose debugging information

Quick Recap

  • try-with-resources attempts to close initialized, non-null resources when Java control flow leaves the block
  • Declare resources in the try header: try (Resource r = new Resource())
  • Multiple resources are closed in reverse order of declaration
  • If close() throws and another exception is active, the close() exception is suppressed and added to the primary exception
  • Use getSuppressed() to retrieve suppressed exception details
  • Variables declared in the header are implicitly final; an existing variable must be final or effectively final (Java 9+)

Interview Questions

1. What is try-with-resources and what problem does it solve?
Try-with-resources is a Java 7 feature that attempts to close initialized, non-null AutoCloseable resources when Java control flow leaves the block. It avoids common missed-close paths in manual cleanup, but cannot run after JVM or process termination.

2. How does try-with-resources handle exceptions from close()?
If close() throws and no other exception is active, that exception propagates normally. If an exception is active and close() also throws, the close() exception is added as a suppressed exception to the primary exception. Use getSuppressed() to retrieve suppressed exceptions."

3. In what order are multiple resources closed?
Multiple resources are closed in reverse declaration order. List dependencies first and dependents after them, so each dependent closes before its dependency.

4. What is a suppressed exception in Java?
A close exception is suppressed when another exception is already primary. If the body completed normally, a close failure is thrown instead. The primary exception exposes suppressed failures through getSuppressed().

5. Can you use try-with-resources without declaring a variable inside the try header?
Java 7 and 8 require a resource declaration in the try header. Since Java 9, you can reference an existing final or effectively final variable there without declaring it again.

6. What is AutoCloseable and how does it relate to Closeable?
AutoCloseable declares close() with a broad Exception contract. Closeable extends it and narrows close() to IOException. InputStream, OutputStream, Reader, and Writer implement Closeable; java.sql.Connection implements AutoCloseable. Custom resources can implement either interface.

7. How do you handle multiple resources with dependencies in try-with-resources?
Declare the dependency first and the dependent resource after it. Reverse-order closing then closes the dependent first. A JDBC chain is a common example: list Connection, then Statement, then ResultSet.

8. What happens if resource initialization throws in try-with-resources?
If initialization throws, that resource is not closed. Any earlier resources that initialized successfully are closed before the exception propagates.

9. Can you nest try-with-resources inside a try-catch block?
Yes. A try-with-resources statement can have catch and finally clauses, and it can be nested inside other try statements. Close failures are suppressed when an earlier exception is already primary; otherwise a close failure is thrown.

10. What is the difference between try-with-resources and manual close() in a finally block?
Try-with-resources attempts to close initialized resources during Java control flow and preserves earlier exceptions by recording later close failures as suppressed. A close failure is thrown if there is no earlier exception. The Java 7 form declares a resource in the header; Java 9+ also allows an existing final or effectively final variable.

11. How does try-with-resources interact with checked exceptions from close()?
If the body completes normally and close() throws, that exception propagates. If the body or an earlier close already failed, a later close exception is added to the primary exception's suppressed list.

12. Can you use try-with-resources with non-AutoCloseable types?
No. The declared or referenced resource must implement AutoCloseable. For cleanup that is not represented by AutoCloseable, use an appropriate explicit cleanup mechanism such as finally.

13. Can a try-with-resources variable be null?
Yes. A null resource is skipped during automatic closing. If the resource is optional, handle its absence explicitly before using it rather than relying on a null value to represent successful setup.

14. How do you handle suppressed exceptions in production code?
When application code logs an exception, most standard stack-trace output includes its suppressed exceptions. If you handle the list directly, iterate over e.getSuppressed(); it may be empty. Avoid replacing the primary exception while reporting cleanup failures.

15. Can you declare a resource as effectively final and still modify it?
The resource variable cannot be reassigned after initialization. An existing variable used with the Java 9+ syntax must be final or effectively final; a variable declared in the try header is implicitly final.

16. What is the performance impact of try-with-resources?
Try-with-resources adds exception-handling logic for cleanup, so the compiler does not promise identical bytecode to a hand-written finally block. Choose it for clear ownership and correct exception handling; benchmark only if cleanup shows up as a real performance concern.

17. Can a resource's close() method throw multiple different exceptions?
One close() invocation can throw one exception. With multiple resources, the first close failure is thrown if the body completed normally, and later close failures are suppressed on it. If the body already failed, close failures are suppressed on the body's exception.

18. What happens when you call close() explicitly on a try-with-resources resource?
Calling close() inside the try block causes a double-close. The resource is closed once by the explicit call and again when the try-with-resources block exits. If close() is idempotent (safe to call twice), this may be harmless. If close() throws on second call, you get an extra exception. Never call close() manually on a managed resource."

19. What happens if several resources throw from close()?
If the body already threw, that body exception remains primary and close failures are suppressed on it. If the body completed normally, the first close failure is thrown and later close failures are suppressed on the first.

20. What is the main advantage of try-with-resources over try-finally?
Try-with-resources closes initialized resources as Java control flow leaves the block and preserves earlier failures when close() also throws. It cannot clean up after process or JVM termination, and a close failure is thrown when no earlier failure exists.

Further Reading

Conclusion

Try-with-resources attempts to close initialized, non-null AutoCloseable resources as Java control flow leaves the block. It closes multiple resources in reverse declaration order. If the body has already failed, later close failures are kept as suppressed exceptions; if the body completed normally, a close failure is thrown. JVM or process termination can interrupt cleanup.

This feature builds on the try-catch-finally foundation covered in Try-Catch-Finally, replacing verbose manual cleanup with declarative resource management. For broader exception handling guidance, Exception Best Practices covers production patterns, and Custom Exceptions explains how to define domain-specific exceptions that integrate with this cleanup model.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals