Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is try-with-resources in Java and why is it better than try-finally?

SHORT ANSWER

It declares AutoCloseable resources in the try parentheses and closes them automatically, in reverse order, even when an exception occurs. It is shorter than try-finally and keeps the original exception when close() also fails.

Explain it simply

When you borrow a book from the college library you must return it, even if the exam got cancelled. Files, database connections and sockets are the same: they must be closed whatever happens. try-with-resources is a librarian who takes every book back for you when you leave.

Example

java
class Res implements AutoCloseable {
    private final String name;
    Res(String name) { this.name = name; System.out.println("open " + name); }
    public void close() { System.out.println("close " + name); }
}

try (Res a = new Res("A"); Res b = new Res("B")) {
    System.out.println("work");
}
// prints:
// open A
// open B
// work
// close B
// close A

What to say in the interview

"Any class implementing AutoCloseable can be declared in the try header. Resources are closed automatically in reverse order of creation, whether the block ends normally or by exception. If both the body and close() throw, the body's exception is the main one and the close exception is attached as suppressed, retrievable with getSuppressed(). The old try-finally pattern would let the close exception hide the real one."

Common mistakes

  • Opening a resource before the try and expecting it to be closed. Only variables declared in the parentheses are managed.

#java#exceptions#try-with-resources

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.