Difficulty: Intermediate
What is try-with-resources? In what order are resources closed, and what happens if both the body and close() throw exceptions?
Before Java 7, closing a file or database connection safely was surprisingly ugly, and even experienced developers got it wrong. Try-with-resources exists to make resource cleanup automatic and correct, so let me explain what problem it solves and how it behaves.
The old style looked like this: open the resource before the try, use it inside, and close it in a finally block, wrapped in another try-catch because close itself can throw. With two resources you needed nested try-finally blocks, and forgetting a null check in finally caused NullPointerExceptions. Worse, if the body threw an exception and then close threw another one, the second exception replaced the first, and you lost the real cause of the failure.
Try-with-resources solves all of this. You declare resources inside parentheses after try, and the compiler generates the cleanup code for you. Any object whose class implements java.lang.AutoCloseable (or its subinterface Closeable, used by streams and readers) can be used. AutoCloseable declares a single method, void close() throws Exception. Connection, Statement, ResultSet, Scanner, InputStream, BufferedReader and ExecutorService (from Java 19) all qualify.
Order of closing is what interviewers ask most. Resources are closed in the reverse order of their creation, like a stack. If you open A then B, B is closed first and then A. This makes sense because B often depends on A, such as a reader wrapped around a stream. The resources are closed before any catch or finally block runs, so by the time your catch executes, the resources are already closed.
If the resource initializer itself throws, only the resources already created are closed. And if a resource expression evaluates to null, close is skipped for it, no NPE.
Now the suppressed exception mechanism, a favourite senior-level question. If the body throws exception X and then close also throws Y, the body's exception X is the one that propagates, and Y is attached to X as a suppressed exception. You can retrieve it with X.getSuppressed(). This is the opposite of the old finally behaviour, and it preserves the primary failure. If only close throws, that exception propagates normally.
Since Java 9 you can use an effectively final variable declared earlier in the try parentheses, so you can write try (reader) without redeclaring it. Also a try-with-resources can have its own catch and finally blocks, and these run after resources are closed.
For your own classes, implement AutoCloseable, keep close idempotent (calling it twice should be harmless), and prefer narrowing the throws clause to specific exceptions or none.
A design tip: use try-with-resources any time you hold something that must be released, including locks wrapped in helper classes, temporary files and test fixtures, not just I/O. Interviewers appreciate that you view it as a general scope-based cleanup tool, similar to RAII in C++ or with statements in Python.
class Res implements AutoCloseable {
private final String name;
Res(String name) {
this.name = name;
System.out.println("open " + name);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public class TwrDemo {
public static void main(String[] args) {
try (Res a = new Res("A"); Res b = new Res("B")) {
System.out.println("body");
}
}
}
Resources are closed in reverse order of declaration, so B is closed before A.
class Bad implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("close failed");
}
}
public class SuppressDemo {
public static void main(String[] args) {
try (Bad b = new Bad()) {
throw new RuntimeException("body failed");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
}
}
}
The body exception is primary. The exception from close is attached as suppressed instead of replacing it.
try-with-resources, AutoCloseable, Suppressed Exceptions, Resource Management