Prior to Java 7, closing external system resources (like files, database connections, sockets) required writing messy, error-prone finally blocks with nested try-catch calls. Try-with-Resources (Automatic Resource Management / ARM) guarantees that every open resource is closed automatically when execution leaves the block.
// Old way: 15+ lines of defensive finally boilerplate
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader("data.txt");
br = new BufferedReader(fr);
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close(); // Can throw ANOTHER IOException!
if (fr != null) fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Resources declared inside parentheses try(...) are closed automatically in reverse order of declaration:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesDemo {
public static void main(String[] args) {
// Resources automatically closed upon exit!
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println("Line: " + line);
}
} catch (IOException e) {
System.err.println("File I/O error: " + e.getMessage());
}
}
}
AutoCloseable Resourcepublic class CustomDatabaseConnection implements AutoCloseable {
public void executeQuery(String sql) {
System.out.println("Executing SQL: " + sql);
}
@Override
public void close() {
System.out.println("[CLEANUP] Database connection closed cleanly!");
}
public static void main(String[] args) {
try (CustomDatabaseConnection db = new CustomDatabaseConnection()) {
db.executeQuery("SELECT * FROM users");
} // db.close() is triggered automatically here!
}
}
Exam Question: "Can a try-with-resources statement have catch and finally blocks?"
Answer: Yes! A try-with-resources block can have catch and finally blocks. Crucially, the automatic close() method is executed BEFORE any catch or finally blocks run.
Congratulations on completing Section 4! Let us now enter Section 5 and explore the Java Collections Framework (Lists, Sets, Maps, Queues). Proceed to: Java Collections Framework Overview →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Traditional exception blocks.
Using try-with-resources with streams.
Closing Connections and Statements.
Entering Section 5: Collections.