Script Valley
Java: Complete Language Course
Exception Handling and I/OLesson 4.3

Java try-with-resources and AutoCloseable

try-with-resources, AutoCloseable, Closeable, resource declaration, automatic close, suppressed exceptions, multiple resources, custom AutoCloseable

try-with-resources

Resource leaks โ€” open files, database connections, and streams that are never closed โ€” are a common Java bug. try-with-resources guarantees close() is called automatically.

Before โ€” Error Prone

BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader("file.txt"));
    System.out.println(br.readLine());
} finally {
    if (br != null) br.close(); // easy to forget; also hides original exception
}

After โ€” Safe and Clean

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} // br.close() called automatically, even if exception occurs

Multiple Resources

try (FileInputStream in  = new FileInputStream("src.txt");
     FileOutputStream out = new FileOutputStream("dst.txt")) {
    in.transferTo(out);
} // closed in reverse order: out first, then in

Custom AutoCloseable

public class DbConnection implements AutoCloseable {
    public DbConnection() { System.out.println("Connected"); }
    @Override
    public void close() { System.out.println("Disconnected"); }
}

try (DbConnection conn = new DbConnection()) {
    conn.query("SELECT 1");
} // Disconnected printed automatically

Any class implementing AutoCloseable works in try-with-resources. Use it for any resource with a lifecycle โ€” file handles, network sockets, database connections, or custom resources.

If an exception occurs in close() while another exception is already propagating, the close exception is added as a suppressed exception on the primary one. Retrieve it via e.getSuppressed(). Classic try-finally would swallow the original exception entirely in this scenario.

Up next

Reading and writing text files in Java

Sign in to track progress

Java try-with-resources and AutoCloseable โ€” Exception Handling and I/O โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley