Java Try-With-Resources
🔧 Java Try-With-Resources (Automatic Resource Management)
When working with resources such as:
-
Files
-
Database connections
-
Network streams
-
Buffered readers/writers
You must close them after use — otherwise memory leaks or file locks may occur.
Traditionally, we used try...finally to close resources.
But since Java 7, we have try-with-resources, which automatically closes resources once the block finishes.
✅ Syntax
The resource must implement the AutoCloseable interface (most Java IO classes already do).
✔️ Example: Reading a File
✔️ What happens automatically?
-
After the
tryblock finishes, -
Java automatically calls
reader.close(), -
Even if an exception occurs.
🔁 Multiple Resources
You can open multiple resources using commas:
⚠️ Before Java 7 (Old Way)
😩 More code + manual cleanup.
⭐ Suppressed Exceptions
If both:
-
The try block throws an exception, and
-
The resource closing also throws an exception
Java saves the second one as a suppressed exception, not lost.
Example:
🧠 Custom Resource Example
To use try-with-resources, your class must implement AutoCloseable.
Output:
🎯 When to Use Try-With-Resources?
| Situation | Recommended |
|---|---|
| File handling | ✔️ Yes |
| Database connections (JDBC) | ✔️ Yes |
| Input/Output streams | ✔️ Yes |
| Anything AutoCloseable | ✔️ Yes |
Summary Table
| Feature | With try-with-resources | With try-finally |
|---|---|---|
| Automatic close | ✔️ Yes | ❌ No |
| Shorter & cleaner code | ✔️ Yes | ❌ No |
| Fewer bugs | ✔️ Yes | ❌ No |
| Suppressed exception tracking | ✔️ Yes | ✔️ But complex |
