Clean • Professional
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.
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).
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:
try (FileInputStream fis = new FileInputStream("data.txt")) {
// read file
} catch (IOException e) {
e.printStackTrace();
}
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
}
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();
}
}
}
To work with try-with-resources, a class must implement:
AutoCloseable (in Java 7+), orCloseable (sub-interface of AutoCloseable)public interface AutoCloseable {
void close() throws Exception;
}
When try block ends, JVM automatically calls:
resource.close();
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
If both:
Then Java suppresses the close exception.
You can view suppressed exceptions using:
for (Throwable t : e.getSuppressed()) {
System.out.println(t);
}
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());
}
| 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 |
Try-with-resources is used in:
Example (JDBC):
try (Connection con = getConnection();
Statement st = con.createStatement()) {
ResultSet rs = st.executeQuery("SELECT * FROM users");
} catch (SQLException e) {
e.printStackTrace();
}