# try-with-resources and AutoCloseable

> What is try-with-resources? In what order are resources closed, and what happens if both the body and close() throw exceptions?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-try-with-resources
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is try-with-resources? In what order are resources closed, and what happens if both the body and close() throw exceptions?

## Answer

Before Java 7, closing a file or database connection safely was surprisingly ugly, and even experienced developers got it wrong. Try-with-resources exists to make resource cleanup automatic and correct, so let me explain what problem it solves and how it behaves.

The old style looked like this: open the resource before the try, use it inside, and close it in a finally block, wrapped in another try-catch because close itself can throw. With two resources you needed nested try-finally blocks, and forgetting a null check in finally caused NullPointerExceptions. Worse, if the body threw an exception and then close threw another one, the second exception replaced the first, and you lost the real cause of the failure.

Try-with-resources solves all of this. You declare resources inside parentheses after try, and the compiler generates the cleanup code for you. Any object whose class implements java.lang.AutoCloseable (or its subinterface Closeable, used by streams and readers) can be used. AutoCloseable declares a single method, void close() throws Exception. Connection, Statement, ResultSet, Scanner, InputStream, BufferedReader and ExecutorService (from Java 19) all qualify.

Order of closing is what interviewers ask most. Resources are closed in the reverse order of their creation, like a stack. If you open A then B, B is closed first and then A. This makes sense because B often depends on A, such as a reader wrapped around a stream. The resources are closed before any catch or finally block runs, so by the time your catch executes, the resources are already closed.

If the resource initializer itself throws, only the resources already created are closed. And if a resource expression evaluates to null, close is skipped for it, no NPE.

Now the suppressed exception mechanism, a favourite senior-level question. If the body throws exception X and then close also throws Y, the body's exception X is the one that propagates, and Y is attached to X as a suppressed exception. You can retrieve it with X.getSuppressed(). This is the opposite of the old finally behaviour, and it preserves the primary failure. If only close throws, that exception propagates normally.

Since Java 9 you can use an effectively final variable declared earlier in the try parentheses, so you can write try (reader) without redeclaring it. Also a try-with-resources can have its own catch and finally blocks, and these run after resources are closed.

For your own classes, implement AutoCloseable, keep close idempotent (calling it twice should be harmless), and prefer narrowing the throws clause to specific exceptions or none.

A design tip: use try-with-resources any time you hold something that must be released, including locks wrapped in helper classes, temporary files and test fixtures, not just I/O. Interviewers appreciate that you view it as a general scope-based cleanup tool, similar to RAII in C++ or with statements in Python.

## Code examples

### Reverse close order

```
class Res implements AutoCloseable {
    private final String name;

    Res(String name) {
        this.name = name;
        System.out.println("open " + name);
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}

public class TwrDemo {
    public static void main(String[] args) {
        try (Res a = new Res("A"); Res b = new Res("B")) {
            System.out.println("body");
        }
    }
}
```

Resources are closed in reverse order of declaration, so B is closed before A.

### Suppressed exceptions

```
class Bad implements AutoCloseable {
    @Override
    public void close() throws Exception {
        throw new Exception("close failed");
    }
}

public class SuppressDemo {
    public static void main(String[] args) {
        try (Bad b = new Bad()) {
            throw new RuntimeException("body failed");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getSuppressed()[0].getMessage());
        }
    }
}
```

The body exception is primary. The exception from close is attached as suppressed instead of replacing it.

## Key points

- Resources must implement AutoCloseable and are declared in the try parentheses.
- They are closed in reverse order, before catch and finally run.
- The primary exception propagates; close exceptions become suppressed.
- Java 9 allows effectively final variables as resources.

## Common follow-up questions

- What is the difference between Closeable and AutoCloseable?
- Can you use try-with-resources without a catch block?
- How do you read suppressed exceptions?
- What happens if the resource is null?

## Interview tips

- Mention reverse closing order and suppressed exceptions; most candidates only say it closes automatically.
- Contrast it with try-finally to show you understand the bug it fixes: the lost original exception.

## Concepts covered

try-with-resources, AutoCloseable, Suppressed Exceptions, Resource Management

Previous: [Checked vs Unchecked Exceptions](https://www.internhack.in/learn/interview/java-interview/java-checked-vs-unchecked-exceptions) · Next: [The Java Collections Framework Hierarchy](https://www.internhack.in/learn/interview/java-interview/java-collections-hierarchy) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [ArrayList vs LinkedList](https://www.internhack.in/learn/interview/java-interview/java-arraylist-vs-linkedlist)
- [How HashMap Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashmap-internals)
- [HashMap vs Hashtable vs ConcurrentHashMap](https://www.internhack.in/learn/interview/java-interview/java-hashmap-hashtable-concurrenthashmap)
- [How HashSet Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashset-internals)
- [Comparable vs Comparator and How TreeMap Sorts](https://www.internhack.in/learn/interview/java-interview/java-comparable-comparator-treemap)
- [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
