Basic Try-With-Resources Syntax
What you'll learn: How to use Java's try-with-resources statement to automatically manage resources without writing explicit cleanup code.
The Core Idea
You've learned that resources like files and database connections need to be closed after use, and that AutoCloseable resources have a close() method. But manually calling close() in a finally block is verbose and error-prone. Java's try-with-resources statement automates this for you.
The syntax is elegantly simple:
try (Resource r = new Resource()) {
// Use the resource
}
// r.close() is called automatically here
Notice the parentheses right after try? That's where you declare and initialize your AutoCloseable resource. When the try block completes—whether normally or via an exception—Java automatically calls close() on the resource for you.
Real Example
try (FileInputStream fis = new FileInputStream("data.txt")) {
int data = fis.read();
// Work with the file
}
// fis.close() called automatically, even if an exception occurred
Without try-with-resources, you'd need multiple lines in a finally block, null checks, and nested exception handling. This syntax collapses all that boilerplate into one clean line.
Multiple Resources
You can manage multiple resources by separating them with semicolons:
try (FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt")) {
// Use both resources
}
// Both close() methods called automatically, in reverse order
Key Takeaway: Try-with-resources syntax try (Resource r = new Resource()) { } automatically closes AutoCloseable resources, eliminating manual cleanup code and ensuring proper resource management even when exceptions occur.