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.
Code
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());
}
}
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.