Try-With-Resources in Java
intermediate· Exceptions · Error Handling
Problem
Try-with-resources automatically calls close() on any resource that implements AutoCloseable once the try block finishes, whether it completes normally or throws — no explicit finally block needed.
Open a custom resource inside a try-with-resources statement and confirm it's closed automatically once the block finishes.
Input
try (Resource r = new Resource()) { r.use(); }
Output
Resource opened
Using resource
Resource closed
Java Program
Java
class Resource implements AutoCloseable {
Resource() {
System.out.println("Resource opened");
}
public void use() {
System.out.println("Using resource");
}
@Override
public void close() {
System.out.println("Resource closed");
}
}
public class TryWithResources {
public static void main(String[] args) {
try (Resource r = new Resource()) {
r.use();
}
// close() already ran automatically before this line, with no explicit finally block
}
}Output
Resource opened
Using resource
Resource closed
Core Logic
Declaring the resource directly in the try statement's parentheses hands its cleanup over to the compiler, which guarantees close() runs once the block ends.
How It Works
- 1
class Resource implements AutoCloseabledeclares a type the try-with-resources syntax knows how to clean up automatically. - 2Its constructor prints
"Resource opened", and itsclose()method prints"Resource closed". - 3
try (Resource r = new Resource()) { ... }creates the resource inside the try statement's own parentheses, rather than before the try block. - 4Once the block inside the braces finishes — here, printing
"Using resource"— the compiler automatically callsr.close(), with no explicitfinallyblock written.
Running the program prints
"Resource opened", then "Using resource" from inside the block, then "Resource closed" automatically once the block ends.💡
Key Point: close() runs automatically even if the block throws an exception partway through — the same guarantee a finally block provides, but without having to write one.
Key Concepts
AutoCloseabletry-with-resourcesautomatic cleanup