try-with-resources
Any code that opens a file, a database connection, or a network stream must eventually close it, or the underlying resource leaks. Since Java 7, try-with-resources automates that cleanup so you can stop writing manual finally blocks just to call close().
The Old Way: Manual finally Cleanup
Before Java 7, closing a resource safely required a verbose try/finally pattern, and it was easy to get subtly wrong — for instance, forgetting that close() itself can throw.
Before Java 7: verbose and error-prone
Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class OldStyleDemo {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("data.txt"));
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("Error closing file: " + e.getMessage());
}
}
}
}
}The New Way: try-with-resources
Declaring a resource inside the parentheses of a try statement guarantees it will be closed automatically when the block exits — normally or via an exception — with no finally needed at all.
Java 7+: clean and safe
Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesDemo {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}The reader is closed automatically the moment the try block finishes, whether it finished normally or by throwing an exception — no risk of a forgotten close() call.
AutoCloseable Is Required
A class can only be used in a try-with-resources statement if it implements the AutoCloseable interface (or its sub-interface, Closeable), which requires a close() method. Most I/O classes, JDBC's Connection, and many third-party client types already implement it.
A custom AutoCloseable resource
Java
public class ManagedResource implements AutoCloseable {
private final String name;
public ManagedResource(String name) {
this.name = name;
System.out.println("Opening " + name);
}
public void use() {
System.out.println("Using " + name);
}
@Override
public void close() {
System.out.println("Closing " + name);
}
}Multiple Resources
You can declare multiple resources in one try-with-resources statement, separated by semicolons.
Multiple resources
Java
public class MultipleResourcesDemo {
public static void main(String[] args) {
try (ManagedResource first = new ManagedResource("first");
ManagedResource second = new ManagedResource("second")) {
first.use();
second.use();
}
}
}Opening first Opening second Using first Using second Closing second Closing first
Note
Resources are closed in the reverse of the order they were declared — second is closed before first. This mirrors how you would manually nest finally blocks, and matters when resources depend on each other (for example, a statement should close before the connection it came from).
Why This Matters
Resource leaks caused by a missed close() call in a finally block used to be one of the most common sources of production bugs in Java — file handles and database connections silently accumulating until the process ran out of them. Try-with-resources virtually eliminates this entire class of bug: the compiler-generated cleanup code cannot be forgotten because there is nothing manual left to write.
Tip
Prefer try-with-resources over manual finally cleanup whenever the resource implements AutoCloseable — which today includes almost every I/O, database, and network client class in the JDK and major libraries.