Java Try-with-Resources: Automatic Resource Management (AutoCloseable)

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.

The Old Painful Way: Pre-Java 7 Boilerplate

// 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();
    }
}

The Modern Way: Clean Try-with-Resources

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());
        }
    }
}

Creating Your Own AutoCloseable Resource

public 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!
    }
}

University Exam Corner (BCA / B.Sc CS)

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.

Next Step

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 →

Frequently Asked Questions (FAQ)

Q1. What is Try-with-Resources in Java?
Introduced in Java 7, Try-with-Resources is an automated resource management statement that automatically closes any resource declared inside its try(...) parenthesis at the end of the statement, eliminating the need for verbose finally blocks.
Q2. What requirement must a resource satisfy to be used in try-with-resources?
The resource class must implement the 'java.lang.AutoCloseable' or 'java.io.Closeable' interface, which mandates the implementation of a public void close() throws Exception method.
Q3. What are Suppressed Exceptions in Java?
If an exception is thrown in the try block AND another exception is thrown when closing the resource automatically, the exception from the try block is delivered to the caller, while the closing exception is attached to it as a 'Suppressed Exception' (retrieved via e.getSuppressed()).

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Try, Catch & Finally →

Traditional exception blocks.

Java File I/O →

Using try-with-resources with streams.

JDBC Database →

Closing Connections and Statements.

Collections Framework →

Entering Section 5: Collections.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!