try-with-resources
Close files, streams and connections automatically, even when the block throws.
Open this lesson in the learning hubKey points
- Anything implementing
AutoCloseablecan be declared intry (...)and Java closes it for you. - Closing happens whether the block finishes normally or throws — and before any
catchorfinallyruns. - Multiple resources close in reverse order of declaration.
- Resource variables are implicitly final. Since Java 9 you can also list an existing effectively-final variable.
- If the body and
close()both throw, the close failure is attached as a suppressed exception rather than lost. - Use it for streams, readers, JDBC connections and sockets — anything you would otherwise close in
finally.
Example
import java.util.Scanner;
public class Main {
static class Connection implements AutoCloseable {
private final String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void run(String sql) { System.out.println(" run " + sql + " on " + name); }
@Override
public void close() { System.out.println("close " + name); }
}
public static void main(String[] args) {
try (Connection a = new Connection("db-1");
Connection b = new Connection("db-2")) {
a.run("select 1");
b.run("select 2");
}
try (Connection c = new Connection("db-3")) {
c.run("select boom");
throw new IllegalStateException("query failed");
} catch (IllegalStateException e) {
System.out.println("close ran before this catch: " + e.getMessage());
}
try (Scanner sc = new Scanner("10 20 30")) {
int total = 0;
while (sc.hasNextInt()) total += sc.nextInt();
System.out.println("scanner total: " + total);
}
}
}
If it is closeable, declare it in the try and never close it by hand.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.