What is try-with-resources in Java and why is it better than try-finally?
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
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 AWhat 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.