Try-With-Resources Syntax
Fast recall
Quick revision
Core answer
AutoCloseable resources in parentheses after try; Java closes successfully initialized resources automatically on normal, exceptional, or abrupt exit.Interview-ready guide
Interview answer
Try-with-resources is Java's language feature for binding a resource's lifetime to a block. A resource is any object whose type implements AutoCloseable. The I/O interface Closeable extends AutoCloseable and narrows close() to IOException, so readers, writers, streams, channels, and many database objects work naturally with the feature.
The syntax places resource declarations in parentheses after try. Java evaluates them, runs the body, and calls close() on each successfully initialized resource whenever control leaves the statement—whether the body completes, returns, or throws. This gives lexical ownership: the source code clearly shows where an acquired resource stops being usable.
For example, try (BufferedReader reader = Files.newBufferedReader(path, UTF_8)) lets code read a line and guarantees that the file-backed reader closes. The caller still handles IOException from opening, reading, or closing; automatic cleanup does not mean failure is ignored.
With multiple resources, initialization occurs left to right and cleanup occurs in reverse order. If a later initializer fails, earlier resources that were created successfully are still closed. If both the body and close throw, the body exception is primary and close exceptions are attached to it as suppressed exceptions instead of replacing the original failure.
Since Java 9, the resource list may also reference a final or effectively-final local variable or parameter, such as try (reader). The reference cannot have been reassigned. Try-with-resources should be the default for resources the block owns, but ownership still matters: do not close a shared resource supplied by another component unless the API contract transfers that responsibility.
Try-With-Resources Syntax
Direct Answer
Try-with-resources declares or references one or more AutoCloseable resources in parentheses after try; Java closes successfully initialized resources automatically on normal, exceptional, or abrupt exit.
Deep Dive & Architecture
Manual cleanup is difficult because a block has more exits than the last visible line: normal completion, checked or unchecked exceptions, return, break, and failures during later resource acquisition. Try-with-resources expands conceptually into nested try/finally logic that closes only resources whose initialization completed. The compiler performs this consistently instead of asking every developer to recreate it.
AutoCloseable.close() may declare Exception, while Closeable.close() declares IOException and specifies idempotent closing. AutoCloseable implementations are encouraged to make close idempotent but are not required to. Generic code must therefore follow the exact contract of the resource it owns and should not casually close it twice.
Automatic close does not imply transaction success. A buffered writer can fail while flushing during close, and a database resource may close after a transaction has already required explicit commit or rollback. Cleanup is one lifecycle stage; the application still defines success, publication, and recovery.
Ownership is the final boundary. A method that creates a reader and fully consumes it should usually close it locally. A method that returns a lazy stream over that reader must either transfer close responsibility clearly or redesign the API. Syntax cannot resolve an ambiguous ownership contract.
Code Example
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
class TryWithResourcesSyntax {
public static void main(String[] args) throws Exception {
Path file = Files.writeString(Files.createTempFile("message-", ".txt"),
"ready", StandardCharsets.UTF_8);
try {
String line;
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
line = reader.readLine();
}
if (!"ready".equals(line)) throw new AssertionError(line);
System.out.println(line);
} finally {
Files.deleteIfExists(file);
}
}
}
Check your understanding
Answer these without looking back at the article.
- How do AutoCloseable and Closeable differ?
- What happens if a later resource initializer fails?
- Does automatic close mean the block owns every resource it receives?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.