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

try (ResourceType resource = new ResourceType()) {
// Use the resource
} catch (Exception e) {
// Handle exception
}

The resource must implement the AutoCloseable interface (most Java IO classes already do).


✔️ Example: Reading a File

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader(“example.txt”))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println(“Error reading file: “ + e.getMessage());
}
}
}

✔️ What happens automatically?

  • After the try block finishes,

  • Java automatically calls reader.close(),

  • Even if an exception occurs.


🔁 Multiple Resources

You can open multiple resources using commas:

try (
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr)
) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}

⚠️ Before Java 7 (Old Way)

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("data.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
System.out.println("Error closing file.");
}
}

😩 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:

try (MyResource r = new MyResource()) {
throw new RuntimeException("Main exception");
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
for (Throwable t : e.getSuppressed()) {
System.out.println("Suppressed: " + t);
}
}

🧠 Custom Resource Example

To use try-with-resources, your class must implement AutoCloseable.

class MyResource implements AutoCloseable {
public void show() {
System.out.println("Using resource");
}
@Override
public void close() {
System.out.println(“Resource closed”);
}
}

public class CustomResourceDemo {
public static void main(String[] args) {
try (MyResource res = new MyResource()) {
res.show();
}
}
}

Output:

Using resource
Resource closed

🎯 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

You may also like...