All topics
exceptions
beginner

try-with-resources

Auto-close anything that implements AutoCloseable — guaranteed cleanup even on exceptions, no boilerplate finally.

Before Java 7, releasing a resource safely meant a verbose and error-prone try/finally dance: open the resource, work with it in the try, and close it in the finally while null-checking and catching the exception that close() itself might throw. People forgot the finally, nested it wrongly for multiple resources, or let a close-time exception mask the real one. The try-with-resources statement makes correct cleanup the default and nearly invisible.

A self-closing door — walk through carrying anything you want, the door always closes behind you. No need to remember.

Key Concepts

1
Any object whose class implements AutoCloseable (or its older subinterface Closeable) can be declared in the parentheses of a try. The compiler guarantees that close() is called automatically when the block exits — whether normally, via an exception, or through a return — so the resource is always released without an explicit finally. You can declare several resources separated by semicolons, and they are closed in reverse order of declaration, which correctly unwinds dependencies like a statement built on a connection. Streams, readers, writers, JDBC connections, and locks are typical resources, and you can make your own classes participate simply by implementing AutoCloseable.
AutoCloseableCloseabletryclose()finally
2
The detail interviewers love is suppressed exceptions. If the body throws and then close() also throws while unwinding, the body's exception is the one that propagates and the close-time exception is attached to it as a suppressed exception (retrievable via getSuppressed()), rather than overwriting the original cause — the opposite of the old hand-written finally, where a throwing close() would hide the real failure. Since Java 9 you can also reference an already-declared effectively-final resource variable directly in the try header, avoiding a redundant re-assignment.
close()getSuppressed()finallytry