← 中文资源

简体中文版本

Java Try-with-Resources 与抑制异常

演示资源按逆序关闭、关闭失败如何作为 suppressed 异常附加到主异常,以及提交标记对回滚语义的影响。

阅读英文原文

功能说明

Transaction 实现 AutoCloseable,只有 committed 为 true 时 close 才正常结束,否则抛出回滚异常。FlushOnClose 的 close 总是失败。第一段 try 正常提交并关闭事务;第二段同时管理事务与刷新器,在提交后主动抛出业务异常,触发逆序关闭。catch 块打印主异常,并遍历 getSuppressed 展示关闭阶段失败的刷新器。

关键代码

try-with-resources 按声明的逆序关闭资源:先关闭 flusher,再关闭 tx,因此 flusher 的失败不会阻止事务关闭。当 try 块已有主异常时,close 抛出的异常会被 addSuppressed 附加,而不是覆盖主异常;若 try 块正常结束,close 异常才会直接向外传播。committed 标志让 close 能区分正常提交与中途失败。catch 中保留原始异常并检查 suppressed,便于日志完整记录。

使用注意

close 方法应尽量幂等,避免重复关闭产生额外异常。示例用运行时异常简化演示,真实资源可能抛出受检异常,close 签名需相应声明。不要为了“清理干净”而吞掉 suppressed 异常,否则会丢失刷新失败等关键信息。事务提交与资源关闭是两件事,提交成功但关闭失败时调用方仍需感知。连接池场景要确认 close 是归还还是物理关闭。

验证方式

运行 main,第一段输出 tx-1 执行与提交后关闭;第二段输出 tx-2 执行、关闭,然后主异常为 batch rejected by business rule,suppressed count 为 1,内容为 buffer-1 flush failed。可去掉 tx.commit 观察主异常变为回滚异常,或让 try 块不抛异常,确认刷新失败直接成为对外异常。

代码示例

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