The Plain Picture#
A hotel room key card that automatically deactivates when you check out — even if you leave in a hurry through the fire exit. You can't forget to hand it back.
The Real Names#
A resource is anything that must be closed when you're done: files, network sockets, database connections. Each holds an operating system handle — a file descriptor (Operating Systems Ch 10). Forgetting to close them leaks descriptors until the program fails with "Too many open files", or a database runs out of connections (Networking 2: TCP, UDP and Ports Ch 12).
try-with-resources (Java 7+) automatically closes resources declared in the
try (...)parentheses, in reverse order, no matter how the block ends.It works with anything implementing the
AutoCloseableinterface (one method:close()— interface segregation, SOLID Principles Ch 5).
Under the Hood#
class Resource implements AutoCloseable {
final String name;
Resource(String name) {
this.name = name;
System.out.println("open " + name);
}
void use(boolean fail) {
System.out.println("use " + name);
if (fail) throw new IllegalStateException("failed using " + name);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
try (Resource a = new Resource("A"); Resource b = new Resource("B")) {
b.use(true); // throws!
} catch (IllegalStateException e) {
System.out.println("caught " + e.getMessage());
}open A
open B
use B
close B ← closed automatically, in REVERSE order of opening...
close A
caught failed using B ← ...and BEFORE the catch block runsThe old way needed a finally with its own try/catch around every close(), and was routinely written wrong.
Suppressed exceptions: if the block throws and close() throws too, the block's exception is the one you receive, and the close()
exception is attached to it as a suppressed exception (e.getSuppressed()) — so neither is lost.
Real uses you'll write:
try (BufferedReader br = new BufferedReader(new FileReader("quiz.txt"))) {
String line;
while ((line = br.readLine()) != null) { ... }
} // file closed here, guaranteedCheck yourself
4 questionsWhat problem does try-with-resources solve?
Show answerHide answer
Guaranteed closing of resources (files, connections) even when exceptions occur, preventing leaks.
In what order are multiple resources closed?
Show answerHide answer
Reverse order of declaration.
What must a class implement to be used in try-with-resources?
Show answerHide answer
AutoCloseable (or its subtype Closeable).
If both the block and close() throw, what happens?
Show answerHide answer
The block's exception is thrown; the close exception is attached as suppressed.