Try-with-Resources in Java
The Try-with-Resources statement was introduced in Java 7 to automatically close resources (like files, connections, streams) without needing a finally block.
It works with any class that implements the AutoCloseable interface.
What is Try-with-Resources?
Try-with-Resources is a feature that allows you to declare resources inside the try statement.
These resources are automatically closed after the try block finishes, even if an exception occurs.
A resource is any object that needs to be closed after usage (e.g., FileReader, Scanner, Connection).
Traditional try-finally (Before Java 7)
You had to manually close resources:
FileInputStream fis = null;
try {
fis = new FileInputStream("data.txt");
// read file
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close(); // must close manually
}
}
Problems:
- Too much code
- Easy to forget closing
- Errors inside finally
- Not clean and readable
Try-with-Resources (After Java 7)
try (FileInputStream fis = new FileInputStream("data.txt")) {
// read file
} catch (IOException e) {
e.printStackTrace();
}
- No need for finally
- Resource closes automatically
- Cleaner and safer
Syntax
try (ResourceType res = new ResourceType()) {
// use resource
} catch (Exception e) {
// handle exception
}
You can also declare multiple resources:
try (Resource1 r1 = new Resource1();
Resource2 r2 = new Resource2()) {
// use r1 and r2
}
Example: Reading a File Using Try-with-Resources
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Resource closes automatically
- No need for finally block
How Does Try-with-Resources Work? (AutoCloseable)
To work with try-with-resources, a class must implement:
AutoCloseable(in Java 7+), orCloseable(sub-interface of AutoCloseable)
AutoCloseable Interface:
public interface AutoCloseable {
void close() throws Exception;
}
When try block ends, JVM automatically calls:
resource.close();
Creating a Custom AutoCloseable Resource
class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Resource closed");
}
}
public class CustomResourceExample {
public static void main(String[] args) {
try (MyResource r = new MyResource()) {
System.out.println("Using resource");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Using resource
Resource closed
Suppressed Exceptions (Important Interview Topic)
If both:
- try block throws an exception
- AND close() also throws an exception
Then Java suppresses the close exception.
You can view suppressed exceptions using:
for (Throwable t : e.getSuppressed()) {
System.out.println(t);
}
Try-with-Resources Without Catch or Finally (Java 9)
Java 9 allows using already declared variables as resources:
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
try (br) { // Java 9 feature
System.out.println(br.readLine());
}
Advantages of Try-with-Resources
| Feature | Benefit |
|---|---|
| Auto-close | No need for finally |
| Clean & short code | More readable |
| Handles suppressed exceptions | Safer |
| Reduces boilerplate | Less code writing |
| Works with any AutoCloseable object | Flexible |
Real-World Use Cases
Try-with-resources is used in:
- File handling (FileReader, BufferedReader, FileInputStream)
- JDBC database operations (Connection, Statement, ResultSet)
- Network connections (Socket)
- Streams (Scanner, PrintWriter)
Example (JDBC):
try (Connection con = getConnection();
Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery("SELECT * FROM users");
} catch (SQLException e) {
e.printStackTrace();
}
