1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: Try-with-resources (Java 7+) automatically closes resources (files, streams, connections) when the try block exits. Resources must implement AutoCloseable. This eliminates verbose finally blocks and prevents resource leaks.
Think of automatic doors. Old way: manually open, do your thing, manually close. Try-with-resources: walk through, door closes automatically behind you!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy: The Self-Closing Umbrella
- Old way (finally): Remember to manually close umbrella when done
- Try-with-resources: Umbrella closes itself automatically
3. Technical Mastery (The "Deep Dive")
Syntax
java
// OLD (manual cleanup)
FileReader fr = null;
try {
fr = new FileReader("file.txt");
// use fr
} finally {
if (fr != null) fr.close();
}
// NEW (automatic cleanup)
try (FileReader fr = new FileReader("file.txt")) {
// use fr
} // Automatically closed here!Multiple Resources
java
try (FileReader fr = new FileReader("in.txt");
FileWriter fw = new FileWriter("out.txt")) {
// Both auto-closed in reverse order
}4. Interactive & Applied Code
java
import java.io.*;
public class TryWithResourcesDemo {
public static void main(String[] args) {
// Example 1: Single resource
singleResource();
// Example 2: Multiple resources
multipleResources();
// Example 3: Custom AutoCloseable
customResource();
}
static void singleResource() {
try (BufferedReader br = new BufferedReader(
new FileReader("data.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
// br.close() called automatically!
}
static void multipleResources() {
try (FileInputStream in = new FileInputStream("in.txt");
FileOutputStream out = new FileOutputStream("out.txt")) {
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
System.out.println("File copied");
} catch (IOException e) {
e.printStackTrace();
}
// Both closed automatically in REVERSE order (out, then in)
}
static void customResource() {
try (MyResource resource = new MyResource()) {
resource.doSomething();
}
// close() called automatically
}
}
// Custom AutoCloseable resource
class MyResource implements AutoCloseable {
public MyResource() {
System.out.println("Resource opened");
}
public void doSomething() {
System.out.println("Using resource");
}
@Override
public void close() {
System.out.println("Resource closed automatically");
}
}5. The Comparison & Decision Layer
| Feature | finally Block | Try-with-Resources |
|---|---|---|
| Verbosity | High (null checks, nested try) | Low (one line) |
| Error-prone | Yes (forget to close) | No (automatic) |
| Suppressed Exceptions | Lost | Preserved via getSuppressed() |
| Java Version | All | 7+ |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question: "What happens if both the try block and close() throw exceptions?" Answer: The try block's exception is the primary exception thrown. The close() exception is suppressed and attached:
java
try (Resource r = new Resource()) {
throw new Exception("Try exception");
} // close() also throws
catch (Exception e) {
e.getMessage(); // "Try exception"
e.getSuppressed(); // Array with close() exception
}Pro-Tip: Implement AutoCloseable for custom resources:
java
class DatabaseConnection implements AutoCloseable {
@Override
public void close() {
// Cleanup code
}
}
try (DatabaseConnection db = new DatabaseConnection()) {
//Use db
} // Auto-closed!