Java · OOP, JVM and backend craft

How does try-with-resources work?

Mediumtry-with-resourcesautocloseableresource managementUpdated Oct 2026
Quiz this track

Short answer

Try-with-resources closes any AutoCloseable declared in its header automatically. Resources close in reverse order, and close failures are attached as suppressed exceptions.

A resource is anything that implements AutoCloseable. The compiler generates a finally block that calls close, so you cannot forget cleanup. If the body throws and close also throws, the body's exception remains primary and the close failure is added as a suppressed exception.

java
try (BufferedReader reader =
         Files.newBufferedReader(Path.of("data.txt"))) {
    return reader.readLine();
}
reader is closed even if readLine throws.

Details worth knowing

  • Multiple resources close in reverse declaration order
  • Java 9 allows an effectively final existing variable in the header
  • Use getSuppressed on the primary exception to inspect close failures
  • A resource that does not need closing should not be put in the header

Try-with-resources is the standard way to manage files, sockets, JDBC statements and locks that implement AutoCloseable. If you write a resource class, implement close idempotently and release native handles promptly rather than waiting for a finalizer.

Catching an exception from close is usually not useful. Suppressed exceptions preserve both failures, and the primary exception is the one that explains the operation.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1In what order are multiple resources closed?
  2. 2What is a suppressed exception?
  3. 3Can you use an existing variable as a resource?
  4. 4What happens if close itself throws?

Say it in the interview

Try-with-resources automatically closes every AutoCloseable declared in the header. The compiler generates the finally logic, and resources close in reverse order. If both the body and close throw, the body exception is primary and the close exception is suppressed. I use it for files, sockets and JDBC resources, and I implement AutoCloseable carefully when I own a resource type.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.