Primary exceptions and suppressed cleanup
Definition:
A suppressed exception records a cleanup failure without discarding the primary failure.
Explanation:
Try-with-resources keeps a primary body failure and attaches later close failures as suppressed exceptions.
Illustration image:
Example:
try (AutoCloseable r = () -> { throw new Exception("close"); }) {
throw new IllegalStateException("body");
} catch (Exception e) {
System.out.println(e.getMessage() + "/" + e.getSuppressed()[0].getMessage());
}Expected behavior. Prints body/close.
Internal working:
If there is no body failure, the first failure encountered during reverse closing becomes primary. Avoid finally returning a value or throwing unconditionally because it can hide the earlier failure. Expose original causes across service boundaries.
Interview questions:
If the body throws and both resources fail to close, which failure reaches catch?
The body failure is primary, and the close failures are attached in reverse-resource close order.