try-with-resources and AutoCloseable
Fast recall
Quick revision
Core answer
try header at block exit — even when an exception is thrown. The compiler desugars it to a finally with suppressed exceptions. Resources must implement `AutoCloseable`; `Closeable` (IO) is a narrower subtype that throws `IOException`.Whether you understand what the compiler generates and the suppressed exception mechanism — a common interview gotcha.
Not knowing about suppressed exceptions. If both the try body and close() throw, the close() exception is suppressed and attached to the body exception, not lost.
Discuss the close ordering (reverse declaration order), how to retrieve suppressed exceptions with Throwable.getSuppressed(), and implementing idempotent close().
Interview-ready guide
Interview answer
Try-with-resources is the compiler generating correct resource cleanup — the old try-finally pattern had a critical flaw where if both the body and close() threw exceptions, the original exception was silently lost.
Suppressed exceptions:
- If the body throws and
close()also throws, the body exception propagates; the close exception is attached viaaddSuppressed() - Retrieve with
getSuppressed()— nothing is lost, unliketry-finallywhere the close exception silently replaces the original
Resource close order:
- Multiple resources close in reverse declaration order — last declared closes first
BufferedReaderwrappingFileInputStream: declare the stream first, reader second; reader closes first (flushes), then stream closes
AutoCloseable contract:
- Any class with a
close()method can implementAutoCloseable Closeableis the narrower I/O variant restrictingclose()to throw onlyIOExceptionclose()should be idempotent — try-with-resources doesn't guarantee single invocation; guard with aclosedflag
I recommend try-with-resources for every resource with a close() method — the compiler handles edge cases that manual cleanup consistently gets wrong.
try-with-resources and AutoCloseable
Direct Answer
try-with-resources (Java 7) calls close() on resources declared in the try header at block exit — even when an exception is thrown. The compiler desugars it to a finally with suppressed exceptions. Resources must implement AutoCloseable; Closeable (IO) is a narrower subtype that throws IOException.
Common Mistakes & Pitfalls
Not knowing about suppressed exceptions. If both the try body and close() throw, the close() exception is suppressed and attached to the body exception, not lost.
Check your understanding
Answer these without looking back at the article.
- How do suppressed exceptions differ from chained exceptions (initCause)?
- What happens if you use try-with-resources with a null resource?
- How would you implement a connection pool with AutoCloseable?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.