What is try-with-resources in Java, and how does it differ from closing a resource in a finally block?
Try-with-resources is a variant of the try statement that declares one or more resources and guarantees they are closed when the block ends — whether it ends normally, by returning, or by throwing. It is the only correct way to handle resource cleanup in modern Java.
Compare it with the manual pattern. The old way needs a finally block, a null check on the resource in case the construction itself threw, and careful ordering so that a failure while closing does not hide the original failure. Try-with-resources replaces all of that with a declaration in the resource specification.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class Main {
public static void main(String[] args) throws IOException {
// The reader is closed automatically when the block ends.
try (BufferedReader reader = new BufferedReader(new StringReader("first\nsecond"))) {
System.out.println("line 1: " + reader.readLine());
System.out.println("line 2: " + reader.readLine());
}
System.out.println("the reader is closed now");
}
}The output shows the two lines read from the reader, and then the confirmation printed after the block — by which point the reader has already been closed, without a single explicit call.
Three advantages over the manual pattern are worth naming. The cleanup happens even if the body throws, which is the whole point. The resource is closed in reverse order of declaration, so nested resources unwind correctly. And if the body throws and close also throws, try-with-resources preserves both: the body's exception propagates and the close exception is attached to it as a suppressed exception, reachable through getSuppressed. The manual finally pattern loses one of them, which is why the compiler even warns about it.
The try-with-resources block is also the natural place to put a resource whose close is expensive, because the JVM closes it at the end of the block whether or not you leave early with a return.