Java Try-with-Resources and Suppressed Errors

See how Java closes resources in reverse order and attaches a failing close to the primary exception as a suppressed throwable.

JavaData Integrity

Code

javasnippet
64 lines
public class ResourceLifecycle {

    static final class Transaction implements AutoCloseable {
        private final String name;
        private boolean committed;

        Transaction(String name) {
            this.name = name;
        }

        void execute(String sql) {
            if (sql == null || sql.isBlank()) {
                throw new IllegalArgumentException("sql must not be blank");
            }
            System.out.println(name + " executing: " + sql);
        }

        void commit() {
            committed = true;
        }

        @Override
        public void close() {
            if (!committed) {
                throw new IllegalStateException(name + " rolled back");
            }
            System.out.println(name + " closed after commit");
        }
    }

    static final class FlushOnClose implements AutoCloseable {
        private final String name;

        FlushOnClose(String name) {
            this.name = name;
        }

        @Override
        public void close() {
            throw new IllegalStateException(name + " flush failed");
        }
    }

    public static void main(String[] args) {
        try (Transaction tx = new Transaction("tx-1")) {
            tx.execute("INSERT INTO audit_log(message) VALUES ('ok')");
            tx.commit();
        }

        try (Transaction tx = new Transaction("tx-2");
             FlushOnClose flusher = new FlushOnClose("buffer-1")) {
            tx.execute("UPDATE accounts SET balance = balance - 10 WHERE id = 1");
            tx.commit();
            throw new IllegalStateException("batch rejected by business rule");
        } catch (IllegalStateException error) {
            System.out.println("primary: " + error.getMessage());
            Throwable[] suppressed = error.getSuppressed();
            System.out.println("suppressed count: " + suppressed.length);
            for (Throwable item : suppressed) {
                System.out.println("suppressed: " + item.getMessage());
            }
        }
    }
}

Inside the snippet

Java Try-with-Resources and Suppressed Errors reduces to the classes ResourceLifecycle, Transaction and FlushOnClose and the functions close and main.

Iteration happens inside for (Throwable item : suppressed) — everything outside it runs once. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block. Invalid states are rejected up front: it throws IllegalArgumentException and IllegalStateException instead of continuing with bad data.

Using it

The primary signature is public void close()

Look for the primary:, suppressed count:, suppressed: prefixes when the file runs; they tie each line to its step.

Key statements

throw new IllegalStateException("batch rejected by business rule");
throw new IllegalArgumentException("sql must not be blank");
throw new IllegalStateException(name + " flush failed");

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code refuses to continue: `IllegalArgumentException` and `IllegalStateException` is thrown while the state is still recoverable.
What does Java Try-with-Resources and Suppressed Errors print when run?
The script runs standalone; its 3 labeled outputs include `primary:`, `suppressed count:`, `suppressed:`.