What is the try-with-resources statement in Java and what problem does it solve?
answer
- Java 7 feature
- resource declared in try(...) header
- implements AutoCloseable
- close() called automatically on exit
- replaces try/finally boilerplate
basics
~20 sIt 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 stry-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// 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 automaticallygo deeper
Knows the basic syntax try(Resource r = ...) and that r is closed automatically, so files and streams do not leak.
Explains that the resource must implement AutoCloseable, that no finally is needed, and contrasts it with the old try/finally idiom.
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().
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)