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.
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
finallyfor cleanup that is not represented by anAutoCloseableresource
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
- Forgetting to declare resources in the header — Objects created in the body are not automatically closed unless another declared resource owns them
- Modifying resource variables — The variable must be effectively final to use in try-with-resources
- Assuming close() never throws — It can, and suppressed exceptions are easy to miss
- Closing resources out of order — While reverse-order closing is correct, interleaved resources can cause confusion
- 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
Further Reading
- Throwable Hierarchy — exception and error class hierarchy in Java
- Try-Catch-Finally — basic exception handling syntax
- Throw and Throws — throwing and declaring exceptions
- Custom Exceptions — creating application-specific exception types
- Exception Best Practices — when and how to use exceptions effectively
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.
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 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.