Java Materials
← Core Java · Chapter 4

Exceptions and resource management

Design exception handling around recovery and ownership. Catch failures where a caller can retry, translate them across architectural boundaries or release resources. Preserve cause and useful diagnostic context while avoiding secret-bearing raw payloads in messages.

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:

Primary exceptions and suppressed cleanup. Body throws · Resource B close fails · Resource A close fails · Primary with two suppressedPrimary exceptions and suppressed cleanupSource or actorBody throwsFirst boundaryResource B close failsInspected stateResource A close failsObservable effectPrimary with two suppressed
Body throws · Resource B close fails · Resource A close fails · Primary with two suppressed

Example:

Worked Java example · see surrounding context in notes
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.

Checked exceptions, recovery and retry

Definition:

Exception translation expresses failure in a caller’s domain while retaining its original cause.

Explanation:

A catch should accomplish recovery, cleanup or useful translation.

Illustration image:

Checked exceptions, recovery and retry. IOException cause · Domain exception · Transient or permanent · Recovery boundaryChecked exceptions, recovery and retrySource or actorIOException causeFirst boundaryDomain exceptionInspected stateTransient or permanentObservable effectRecovery boundary
IOException cause · Domain exception · Transient or permanent · Recovery boundary

Example:

Worked Java example · see surrounding context in notes
try { return java.nio.file.Files.readString(path); }
catch (java.io.IOException e) {
    throw new java.io.UncheckedIOException("Cannot load policy file", e);
}

Expected behavior. The caller sees an application-relevant message and can still inspect the IOException.

Internal working:

Retrying malformed input or an authorization failure wastes work. A transient remote timeout has an unknown outcome for a write; retry only under a safe idempotency contract. Preserve the cause and use a redacted message suitable for logs.

Interview questions:

When should a read failure be retried?

Retry only when classified as transient and within the operation budget. A write with an unknown outcome needs idempotency or reconciliation.

Interruption and cleanup

Definition:

Interruption is a cooperative cancellation signal for a thread.

Explanation:

Some blocking methods throw InterruptedException and clear the flag.

Illustration image:

Interruption and cleanup. Worker waiting · Interrupt requested · Blocking call throws · Cleanup and exitInterruption and cleanupSource or actorWorker waitingFirst boundaryInterrupt requestedInspected stateBlocking call throwsObservable effectCleanup and exit
Worker waiting · Interrupt requested · Blocking call throws · Cleanup and exit

Example:

Worked Java example · see surrounding context in notes
try { queue.take(); }
catch (InterruptedException stopped) {
    Thread.currentThread().interrupt();
    return;
}

Expected behavior. The interrupted worker leaves the code path and higher layers can still see its interrupt status.

Internal working:

Rethrow when the API allows it. Otherwise restore the flag and return or translate cancellation. Use try-with-resources and finally to release acquired state. Do not turn cancellation into a retry loop that resumes the work the caller asked to stop.

Interview questions:

Why call interrupt again after catching InterruptedException?

Many blocking methods clear the flag when they throw. Restore it if you cannot propagate the checked exception and the boundary still needs cancellation status.

Reference subtopics

Throwable and propagation

Error typically indicates serious VM or environment conditions. Checked exceptions must be caught or declared. RuntimeException represents unchecked failures. throw raises an instance; throws declares part of a method contract. Catch narrower types before broader ones. Multi-catch alternatives cannot have a subtype relationship.

finally and suppressed failures

finally generally runs on normal and exceptional exit, but JVM termination can prevent it. Returning or throwing from finally can hide the earlier result or failure. Try-with-resources closes in reverse order; if the body throws and close also throws, the close failure is suppressed on the primary exception. Inspect getSuppressed during diagnosis.

Translation and interruption

Expose a domain-specific exception when a caller needs business context; pass the original cause. Propagate InterruptedException when possible. When a boundary cannot rethrow it, restore the interrupt flag with Thread.currentThread().interrupt() and leave promptly. Swallowing interruption can cause shutdown or cancellation to stall.

Run the complete Java labs ↗ · Java reference ↗