Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Why should you prefer try-with-resources over try-finally for closing resources in Java?

try-with-resources closes every resource it declares automatically, in reverse order of creation, even when the body throws. If both the body and close() throw, the body's exception is the one we see and the close exception is attached to it as a suppressed exception, whereas with try-finally an exception from close() can replace and hide the original. The code is shorter, much harder to get wrong with several resources, and it works with anything that implements AutoCloseable.

Why this question is asked

Leaking resources is one of the quietest ways to bring a Java service down. A forgotten close() on a JDBC connection does not fail a test; it slowly drains the connection pool until requests start timing out under load. Interviewers ask about try-with-resources because the answer shows whether we understand exception handling in detail, especially what happens when cleanup itself fails. In this answer, we will recap what a resource is, look at the try-finally pattern and its two weaknesses, see how try-with-resources solves them, check the closing order with several resources, and finish with the details that still catch people out.

1A Quick Recap of Resources and AutoCloseable

A resource is an object that holds something outside the Java heap that must be released explicitly: a file handle, a socket, a database connection, a lock. The garbage collector frees memory, but it does not promptly release file handles or return connections to a pool, so we must call close() ourselves, and we must do it even when an exception interrupts our code.

Java expresses this with the AutoCloseable interface, which has a single method, void close() throws Exception. Closeable, used by IO streams, extends it. Any class implementing AutoCloseable can be used with try-with-resources, including our own classes.

2The try-finally Pattern and Its Problems

Before Java 7, the correct way to close a resource was a finally block. We will use a small test resource that fails both when used and when closed, to see what happens.

Java
class Res implements AutoCloseable {
void use() { throw new IllegalStateException("body failed"); }
public void close() { throw new IllegalStateException("close failed"); }
}
Res r = new Res();
try {
r.use();
} finally {
r.close();
}
// Exception in thread "main" java.lang.IllegalStateException: close failed
// "body failed" is gone: no trace of it anywhere

This is the serious weakness. When a finally block throws, its exception replaces the one already in flight. The real problem, the body failure, is lost, and we spend hours debugging a close error that was only a side effect. In real code this happens when a network drops: the write fails, and then close() fails too because the connection is dead, and the log only shows the close.

The second weakness is verbosity with several resources. To close two resources safely we need nested try-finally blocks, or null checks and try-catch inside the finally, and that code is easy to get subtly wrong, for example by not closing the second resource when closing the first throws.

3The Same Code With try-with-resources

With try-with-resources, we declare the resource in parentheses after try. Java generates the closing code for us, and it handles the double failure correctly.

Java
try (Res r = new Res()) {
r.use();
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // body failed
System.out.println(e.getSuppressed()[0].getMessage()); // close failed
}
// Stack trace of e would show:
// java.lang.IllegalStateException: body failed
// Suppressed: java.lang.IllegalStateException: close failed
Step throughHow try-with-resources ends
  1. Open resources in orderA, then B
  2. Run the body
  3. Did the body throw?
    YesRemember it as the primary exceptionNoNo primary exception yet
  4. Close resources in reverse orderB, then A; every one is closed
  5. Did a close() throw?
    YesAdd as suppressed if there is a primary, otherwise it becomes primaryNoNothing extra
  6. Rethrow the primary exception, if anythen catch and finally blocks run

6 steps in order. Play them, or step through them one at a time.

Notice that the body's exception is the one that propagates, because it is almost always the one that explains what went wrong. The close exception is not thrown away either: Java attaches it with addSuppressed(), and it appears in the stack trace under 'Suppressed:'. If only close() throws, that exception propagates normally, so a failed close is never silently ignored. Also notice that the catch block runs after the resource has already been closed.

4Several Resources Close in Reverse Order

With several resources, we separate them with semicolons. They are closed in the reverse order of creation, which matters because later resources often depend on earlier ones, such as a statement that depends on its connection.

Java
record Named(String name) implements AutoCloseable {
Named { System.out.println("open " + name); }
public void close() { System.out.println("close " + name); }
}
try (var a = new Named("A"); var b = new Named("B")) {
System.out.println("body");
}
// open A
// open B
// body
// close B
// close A
try (Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("select name from customer where id = ?")) {
ps.setLong(1, 42);
try (ResultSet rs = ps.executeQuery()) { ... }
} // result set, statement, then connection: all closed, even on SQLException

Every resource that was successfully opened is closed, even if closing an earlier one throws. Getting all of that right by hand with nested finally blocks is exactly the kind of code that has bugs, which is why the compiler-generated version is safer as well as shorter.

5Details That Still Catch People Out

Only resources that were successfully created are closed. If we write try (var in = new BufferedReader(new FileReader(file))) and the BufferedReader constructor throws, the inner FileReader is not a declared resource, so nothing closes it. For wrappers whose constructors can fail, declare each layer as its own resource. In practice the JDK's buffered wrappers rarely throw, but the rule matters for our own wrapping classes.

Since Java 9, we can also use an existing variable as a resource, as long as it is final or effectively final: try (connection) { ... }. And many JDK types are AutoCloseable now, including ExecutorService since Java 19, whose close() waits for submitted tasks to finish, so try (var executor = Executors.newVirtualThreadPerTaskExecutor()) is a common idiom with virtual threads.

6Follow-up questions

Is there any reason left to use try-finally?

Yes, for cleanup that is not closing a resource, such as unlocking a ReentrantLock with lock.unlock() in a finally block, or restoring a thread-local value. A lock is not AutoCloseable, and wrapping it just to use try-with-resources often obscures the intent. For anything that implements AutoCloseable, try-with-resources is the better choice.

How do you see suppressed exceptions in logs?

Most logging frameworks, including Logback and Log4j 2, print them automatically as 'Suppressed:' sections of the stack trace when we log the exception object. In code, Throwable.getSuppressed() returns them as an array. They are only lost if we log e.getMessage() instead of the exception itself.

Does Spring's JdbcTemplate or JPA make this unnecessary?

Mostly, for database access. JdbcTemplate and the EntityManager managed by Spring open and close connections for us, which is one reason to use them. But we still write try-with-resources for files, streams, HTTP response bodies, and resources such as Stream objects from Files.lines() or from repository methods that return a Stream, which hold a cursor until closed.

7Conclusion

In this answer, we saw that try-finally can lose the real exception when close() also throws, and becomes verbose and fragile with several resources. try-with-resources closes every successfully opened resource automatically in reverse order, keeps the body's exception as the primary one, attaches close failures as suppressed exceptions, and works with any AutoCloseable. We also saw the remaining pitfalls: wrapped constructors and the cases where finally is still the right tool.

What to say in the interviewAbout 90 seconds aloud

Open with

I prefer try-with-resources because it is both safer and shorter. Any resource I declare in the parentheses, anything implementing AutoCloseable, is closed automatically when the block ends, whether the body completes or throws.

Then, if they want more

With several resources, they are closed in reverse order of creation, so a ResultSet closes before its statement and the statement before its connection, and every one that was opened gets closed even if closing another one fails. The more subtle reason is exception handling.

With try-finally, if the body throws and then close throws too, the exception from the finally block replaces the original, so the real cause disappears from the logs.

That happens in practice when a network connection dies: the write fails, then close fails, and we only see the close error. try-with-resources keeps the body's exception as the primary one and attaches the close exception to it as a suppressed exception, which shows up in the stack trace under Suppressed.

If only close throws, that exception is thrown normally, so nothing is silently ignored. Writing all that correctly by hand with nested finally blocks is error prone, which is why the compiler-generated version is better.

One detail I watch for is wrapped constructors: only declared resources are closed, so if a wrapper's constructor can throw, I declare the inner resource separately. I still use finally for things that are not resources, like unlocking a lock.

About this answer

Last updated
12 November 2026
Versions it names
Java 19, Java 7, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why should you prefer try-with-resources over try-finally for closing resources in Java?": https://scrivio-interview-library.netlify.app/java/clean-code/c2008c1453/