Skip to main content

Lesson 3 of 8

try-with-resources - Auto-closeable

try-with-resources (Java 7+) automatically closes resources (files, connections, streams) when the block exits - whether normally or via exception. It replaces the verbose and error-prone try-catch-finally+close() pattern. Every I/O and JDBC code should use it.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

AutoCloseable & try-with-resources

AutoCloseable & try-with-resources
import java.io.*;
import java.sql.*;

public class TryWithResources {

    // ❌ OLD WAY - verbose, error-prone (what if close() itself throws?)
    public static String readOldWay(String path) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            return reader.readLine();
        } catch (IOException e) {
            throw e;
        } finally {
            if (reader != null) {   // must null-check
                reader.close();     // this can also throw IOException!
            }
        }
    }

    // ✅ MODERN - try-with-resources (auto-closes BufferedReader)
    public static String readModern(String path) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            return reader.readLine();
        }
        // reader.close() called automatically - even if exception thrown
    }

    // Multiple resources - closed in REVERSE order of declaration
    public static void copyFile(String src, String dst) throws IOException {
        try (
            InputStream  in  = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst)
        ) {
            in.transferTo(out);  // Java 9+ - copies all bytes
        }
        // out.close() called first, then in.close()
    }

    // Custom AutoCloseable resource
    public static class DatabaseConnection implements AutoCloseable {
        private final String url;
        private boolean connected;

        public DatabaseConnection(String url) {
            this.url = url;
            this.connected = true;
            System.out.println("Opened connection: " + url);
        }

        public void query(String sql) {
            if (!connected) throw new IllegalStateException("Connection closed");
            System.out.println("Executing: " + sql);
        }

        @Override
        public void close() {  // called automatically by try-with-resources
            connected = false;
            System.out.println("Closed connection: " + url);
        }
    }

    public static void main(String[] args) {
        // Custom AutoCloseable in try-with-resources
        try (DatabaseConnection conn = new DatabaseConnection("jdbc:postgresql://localhost/library")) {
            conn.query("SELECT * FROM books WHERE available = true");
        }
        // "Closed connection: ..." printed automatically
    }
}

Quick Quiz

Tip

Tip

Practice trywithresources Autocloseable in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for try-with-resources - Auto-closeable

Practice Task

Note

Practice Task - (1) Write a working example of trywithresources Autocloseable from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with trywithresources Autocloseable is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done