Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Exception Handling & Custom Exceptions

Walk through how try-with-resources works and why it's strictly better than finally-based cleanup.

Level II · JuniorException Handling & Custom Exceptions
Short answer

try-with-resources auto-closes any AutoCloseable declared in its header, in reverse order of acquisition, generating the close() calls for you.

Explanation

It's better than a finally block because manual finally cleanup is verbose and, critically, an exception thrown by close() in a finally can suppress the original exception from the try body — try-with-resources instead attaches close() failures as suppressed exceptions (getSuppressed()), so you never lose the root cause. It also correctly handles multiple resources without nested finallys.

Common mistakes
  • Forgetting resources close in reverse order of declaration.
  • Using try-with-resources on objects that are not AutoCloseable.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Exception Handling & Custom Exceptions.

Practise free

More on Exception Handling & Custom Exceptions