Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Exceptions and Generics

    try-with-resources

    A resource is anything that must be closed when you're done: files, network sockets, database connections. Each holds an operating

    Chapter 4 of 103 min read

    The Plain Picture#

    A hotel room key card that automatically deactivates when you check out — even if you leave in a hurry through the fire exit. You can't forget to hand it back.

    The Real Names#

    • A resource is anything that must be closed when you're done: files, network sockets, database connections. Each holds an operating system handle — a file descriptor (Operating Systems Ch 10). Forgetting to close them leaks descriptors until the program fails with "Too many open files", or a database runs out of connections (Networking 2: TCP, UDP and Ports Ch 12).

    • try-with-resources (Java 7+) automatically closes resources declared in the try (...) parentheses, in reverse order, no matter how the block ends.

    • It works with anything implementing the AutoCloseable interface (one method: close() — interface segregation, SOLID Principles Ch 5).

    Under the Hood#

    Java
    class Resource implements AutoCloseable {
        final String name;
    
        Resource(String name) {
            this.name = name;
            System.out.println("open " + name);
        }
    
        void use(boolean fail) {
            System.out.println("use " + name);
            if (fail) throw new IllegalStateException("failed using " + name);
        }
    
        @Override
        public void close() {
            System.out.println("close " + name);
        }
    }
    
    try (Resource a = new Resource("A"); Resource b = new Resource("B")) {
        b.use(true); // throws!
    } catch (IllegalStateException e) {
        System.out.println("caught " + e.getMessage());
    }
    Output
    open A
    open B
    use B
    close B            ← closed automatically, in REVERSE order of opening...
    close A
    caught failed using B     ← ...and BEFORE the catch block runs

    The old way needed a finally with its own try/catch around every close(), and was routinely written wrong.

    Suppressed exceptions: if the block throws and close() throws too, the block's exception is the one you receive, and the close() exception is attached to it as a suppressed exception (e.getSuppressed()) — so neither is lost.

    Real uses you'll write:

    Java
    try (BufferedReader br = new BufferedReader(new FileReader("quiz.txt"))) {
        String line;
        while ((line = br.readLine()) != null) { ... }
    }                                                   // file closed here, guaranteed

    Check yourself

    4 questions
    1

    What problem does try-with-resources solve?

    Show answer

    Guaranteed closing of resources (files, connections) even when exceptions occur, preventing leaks.

    2

    In what order are multiple resources closed?

    Show answer

    Reverse order of declaration.

    3

    What must a class implement to be used in try-with-resources?

    Show answer

    AutoCloseable (or its subtype Closeable).

    4

    If both the block and close() throw, what happens?

    Show answer

    The block's exception is thrown; the close exception is attached as suppressed.