skip to content

try-with-resources

Resources declared in the header are closed automatically in reverse order, and if both the body and close throw, the close exception is attached as suppressed rather than masking the real failure. That suppressed-exception behavior is exactly the bug the old finally idiom had, and is what interviewers probe.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What is the try-with-resources statement in Java and what problem does it solve?

level: juniorimportance: must knowfreq 78%

answer

  1. Java 7 feature
  2. resource declared in try(...) header
  3. implements AutoCloseable
  4. close() called automatically on exit
  5. replaces try/finally boilerplate

basics

~20 s

It is a try block that declares resources (like a file or connection) in parentheses. Java automatically closes them when the block ends, even if an error happens, so you do not need a finally block to close them yourself.

solid answer

~40 s

try-with-resources, added in Java 7, is a form of the try statement where you declare one or more resources inside parentheses after the try keyword. A resource is any object implementing AutoCloseable. When the try block finishes, normally or because of an exception, the JVM automatically calls close() on each declared resource. This replaces the old, error-prone try/finally pattern of opening a resource, using it, and closing it in finally, which was verbose and easy to get wrong (forgetting null checks, swallowing exceptions, closing in the wrong order). The benefit is guaranteed, leak-free cleanup of files, streams, sockets, and database connections with far less boilerplate.

code

java · 12 lines
java
// Old way
FileInputStream in = new FileInputStream("a.txt");
try {
    System.out.println(in.read());
} finally {
    in.close();
}

// try-with-resources
try (FileInputStream in2 = new FileInputStream("a.txt")) {
    System.out.println(in2.read());
} // in2.close() called automatically

go deeper

for a junior

Knows the basic syntax try(Resource r = ...) and that r is closed automatically, so files and streams do not leak.

for a middle

Explains that the resource must implement AutoCloseable, that no finally is needed, and contrasts it with the old try/finally idiom.

for a senior

Articulates the exact close-on-exit guarantee, that catch/finally are optional and run after closing, and why GC is not a substitute for deterministic close().

for a principal

Frames it as deterministic resource management in a GC language, discusses API design implications (making your types AutoCloseable), and team conventions for guaranteeing no leaks.

## The problem: resource leaks Many objects in Java hold an **operating-system resource** that lives outside the Java heap: an open file handle, a network socket, a database connection, a lock. These are limited; if you keep opening them without closing them the program eventually fails ("too many open files"). The garbage collector frees memory but does **not** reliably or promptly close such resources, so you must close them explicitly. ## The old way: try/finally Before Java 7 you wrote: ```java FileInputStream in = new FileInputStream("a.txt"); try { // use in } finally { in.close(); // runs whether or not an exception is thrown } ``` A `finally` block always runs after the `try` body, so `close()` runs even on an exception. But this is verbose, and with two resources you nest it and add null checks, and `close()` itself can throw and mask the real error. ## try-with-resources Since Java 7 you declare the resource in parentheses after `try`: ```java try (FileInputStream in = new FileInputStream("a.txt")) { // use in } // in.close() is called automatically here ``` The variable `in` is a **resource**. The only requirement is that its type implements the `AutoCloseable` interface (which declares a single method, `void close() throws Exception`). When control leaves the `try` block for any reason, the compiler-generated code calls `in.close()` automatically. You write no `finally`. ## Why it is better - **No leaks**: cleanup is guaranteed by the language, not by remembering to write it. - **Less code**: no `finally`, no null checks. - **Correct exception behavior**: if both the body and `close()` throw, the body's exception is the one propagated and the `close()` exception is attached as a *suppressed* exception (it is not lost). ## Key terms - **Resource**: an object you must release; in this context, one declared in the try header. - **AutoCloseable**: the interface that makes a type usable as a resource. - **close()**: the method the JVM calls to release the resource. In short, try-with-resources turns manual, fragile cleanup into an automatic, language-guaranteed one.

  • Does try-with-resources require a catch or finally block?
    No. A try-with-resources can stand alone with neither catch nor finally; the closing is implicit. You may still add catch and/or finally if you need them, and they run after the resources are closed.
  • What interface must a class implement to be used as a resource?
    AutoCloseable (or its subinterface Closeable). Implementing AutoCloseable is the only requirement.

saying these in an interview costs you the question

  • Thinking the garbage collector closes files/sockets for you
  • Claiming you still need a finally block to close the resource
  • Believing it was always in Java (it arrived in Java 7)

context

open as a page

Explain the AutoCloseable and Closeable interfaces and the contract of close().

level: middleimportance: must knowfreq 60%

basics

~20 s

AutoCloseable is an interface with one method, close(), that releases a resource. Closeable is a more specific version for I/O. A class implementing either can be used in try-with-resources, and close() should free whatever the object is holding.

open as a page

What are suppressed exceptions in try-with-resources, and what happens when both the try body and close() throw?

level: seniorimportance: must knowfreq 58%

basics

~20 s

If the code in the try block throws an error and then close() also throws, Java keeps the first error (from the body) as the one you see, and attaches the close() error to it as a suppressed exception, which you can read later with getSuppressed().

open as a page

If multiple resources are declared in one try-with-resources header, in what order are they closed and why?

level: middleimportance: should knowfreq 52%

basics

~10 s

They are closed in the reverse order they were declared. The last one opened is the first one closed, like a stack, so a resource that depends on an earlier one is closed first.

open as a page

Can a try-with-resources use a resource variable declared outside the try header? Explain effectively-final resources (Java 9+).

level: seniorimportance: should knowfreq 40%

basics

~20 s

Yes, since Java 9. If a resource is already stored in a final or effectively-final variable, you can just name that variable inside try(...) instead of declaring a new one, and Java still closes it automatically.

open as a page