he try-with-resources mechanism in Java is a feature introduced in Java 7 that automatically closes resources (such as files, sockets, and database connections) when they are no longer needed.
It eliminates the need for explicitly closing resources in a finally block, reducing boilerplate code and preventing resource leaks.
1. Syntax of try-with-resources
try (ResourceType resourceName = new ResourceType()) {
// Code that uses the resource
} catch (ExceptionType e) {
// Handle exception
}
- The resource must implement the
AutoCloseableorCloseableinterface. - The resource is automatically closed when the
tryblock exits.
2. Example Without try-with-resources (Traditional Way)
Before Java 7, resources had to be manually closed inside a finally block.
import java.io.*;
public class TraditionalFileHandling {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
} finally {
try {
if (br != null) {
br.close(); // Must manually close resource
}
} catch (IOException e) {
System.out.println("Error while closing resource.");
}
}
}
}
🛑 Problems with this approach:
- Boilerplate code: Need to check for
nulland explicitly close the resource. - Potential resource leak: If
close()is forgotten, it can lead to memory issues. - Nested
try-catch: Handling closing errors increases complexity.
3. Example Using try-with-resources (Modern Approach)
With try-with-resources, resources are closed automatically when the try block exits.
import java.io.*;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}
✅ Advantages of this approach:
✔ No need to manually close resources.
✔ Code is cleaner and more readable.
✔ No risk of resource leaks.
4. Multiple Resources in try-with-resources
You can declare multiple resources inside the try statement.
✅ Example: Handling Multiple Resources
import java.io.*;
public class MultipleResourcesExample {
public static void main(String[] args) {
try (
FileReader file = new FileReader("test.txt");
BufferedReader br = new BufferedReader(file)
) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}
✅ Both resources (FileReader and BufferedReader) will be closed automatically!
5. How Does try-with-resources Work Internally?
When using try-with-resources, Java internally calls the close() method on each resource in reverse order after the try block executes.
Equivalent manual closing version:
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
try {
System.out.println(br.readLine());
} finally {
br.close(); // Auto-invoked in try-with-resources
}
6. Custom Resource with AutoCloseable
You can create your own resource that works with try-with-resources by implementing AutoCloseable.
✅ Example: Custom AutoCloseable Resource
class MyResource implements AutoCloseable {
public MyResource() {
System.out.println("Resource Created");
}
public void doSomething() {
System.out.println("Doing something...");
}
@Override
public void close() {
System.out.println("Resource Closed");
}
}
public class CustomAutoCloseableExample {
public static void main(String[] args) {
try (MyResource res = new MyResource()) {
res.doSomething();
}
}
}
✅ Output:
Resource Created
Doing something...
Resource Closed
🔹 Key Takeaway: The close() method is automatically called when the try block exits.
7. try-with-resources vs. finally
| Feature | try-with-resources | finally |
|---|---|---|
| Code Complexity | ✅ Cleaner, no extra try-catch | ❌ More lines, requires explicit closing |
| Automatic Closing? | ✅ Yes | ❌ No (must manually close) |
| Multiple Resources | ✅ Easily handles multiple resources | ❌ Requires multiple try-catch blocks |
| Error Handling | ✅ Less prone to resource leaks | ❌ Risk of missing close() |
8. When to Use try-with-resources?
✔ When working with files, database connections, or network sockets.
✔ When using AutoCloseable or Closeable resources.
✔ When you want to avoid manual resource management.
9. Summary
🔹 try-with-resources (Java 7+) automatically closes resources, reducing boilerplate code.
🔹 It requires resources to implement AutoCloseable or Closeable.
🔹 Multiple resources can be handled in one try statement.
🔹 Custom resources can be created by implementing AutoCloseable.