Observe primary and suppressed failures across body, initialization and reverse-order cleanup.
Cleanup can fail after the useful work already failed
A synthetic worker opens two resources, begins processing and throws an exception. While the stack unwinds, both resources also fail to close. Which exception should reach the caller? If cleanup replaces the original processing failure, the report points at the wrong first problem. If cleanup failures disappear entirely, the report hides evidence that resources may not have been released correctly. Java's try-with-resources preserves both kinds of information through primary and suppressed exceptions.
This is an evergreen Java behavior, not a new JDK feature. It matters when an agent harness launches deterministic code, when a service manages streams, and whenever a worker has several resources whose lifetimes overlap. The useful lesson is not merely to close resources automatically. It is to retain the relationship between the initial failure and the additional failures encountered while cleaning up.
The worked example uses in-memory objects that deliberately throw from close. It opens no files, sockets or database connections. That makes the sequence reproducible without relying on a real storage outage. The fixture is small enough to reason about every event, while exposing the same exception-selection rules a larger application needs to preserve in its logs and error adapters.
Understand the primary exception before adding wrappers
The Java language specification defines resources as closing in reverse initialization order. A failure while closing one resource does not prevent attempts to close the others. If the body has already thrown, that exception remains primary and cleanup failures are attached as suppressed exceptions. If the body completes normally but cleanup fails, the first cleanup failure becomes primary and later cleanup failures are suppressed beneath it.
Initialization is part of this story. If the second resource's initializer throws, the first successfully initialized resource still needs cleanup. The second resource is not closed because its initialization did not complete successfully. If closing the first resource then fails, that cleanup failure is suppressed beneath the initialization failure. The body is never entered, which is an important distinction when attributing whether any work began.
Suppression and causation are different relationships. A cause usually explains why an exception was thrown. A suppressed exception records another failure that occurred while an earlier one was already propagating. Flattening both into one string loses that structure. Keep the exception object, its cause chain and its suppressed list when passing failures through a local adapter or a diagnostic serializer.
Observe a complete failure sequence
This original Java example gives each resource a name so the output shows reverse-order cleanup. The assertion checks the primary exception and both suppressed exceptions; it does not merely verify that something was thrown. Run it with assertions enabled. A production logger generally prints the exception object and stack trace rather than recreating the short demonstration output shown here.
// Author: Sandeep Belgavi. Original synthetic cleanup failure example.
public class SuppressedExample {
static final class Resource implements AutoCloseable {
private final String name;
Resource(String name) { this.name = name; }
@Override public void close() {
throw new IllegalStateException("close:" + name);
}
}
public static void main(String[] args) {
try (var input = new Resource("input");
var output = new Resource("output")) {
throw new IllegalArgumentException("body:invalid fixture");
} catch (RuntimeException failure) {
assert failure.getMessage().equals("body:invalid fixture");
Throwable[] secondary = failure.getSuppressed();
assert secondary.length == 2;
assert secondary[0].getMessage().equals("close:output");
assert secondary[1].getMessage().equals("close:input");
System.out.println(failure.getMessage());
for (Throwable item : secondary) {
System.out.println("suppressed:" + item.getMessage());
}
}
}
}The expected output is the body failure followed by the output cleanup failure and then the input cleanup failure, each marked as suppressed. The output does not prove that a real resource was released, because the fixture deliberately models unsuccessful closes. It proves the ordering and preservation of failure evidence for this program. A test harness should separately record which close methods were attempted.
Avoid the finally block that replaces the evidence
A tempting manual pattern is to call the body in a try and close the resource in finally. If both throw, the finally failure can replace the body failure. Another tempting pattern catches and ignores every cleanup error, which preserves the first failure but loses the additional evidence. Try-with-resources provides a defined composition rule so application code does not have to reimplement it at every resource boundary.
Wrapping a failure can lose evidence too. Throwing a new exception containing only the original message drops the original stack, cause and suppressed list. Prefer a wrapper that retains the original exception as its cause when an abstraction boundary requires a new type. If a remote response cannot carry Java exceptions directly, serialize a bounded diagnostic structure with explicit primary, cause and suppressed relationships.
Do not expose unrestricted exception messages to untrusted callers. Paths, SQL text or internal identifiers can appear in real failures. Keep detailed diagnostics in the appropriate local logging channel and return a stable public error code with a correlation identifier. Redaction should preserve the relationship between failures even when their messages are shortened or replaced.
Decide retry policy from the whole outcome
A cleanup failure does not automatically mean the body failed before producing effects. A writer might finish its main work and then fail while flushing or closing. Conversely, the body may fail before any effect while cleanup reports a separate resource problem. A generic retry wrapper that sees only a single exception class cannot infer whether replay is safe. The operation needs an explicit effect and idempotency contract.
For a synthetic transformation, retrying may be harmless because it has no external side effects. For a real adapter, separate result durability from resource cleanup. A successful calculation whose result could not be persisted should not be reported as a durable success. A failed close after a remote effect may leave an unknown outcome that requires reconciliation. Suppressed exceptions improve evidence; they do not resolve uncertainty about external state.
Cancellation deserves similar care. A worker interrupted during processing may still encounter failures during cleanup. Preserve the interruption or cancellation signal according to the runtime's contract rather than replacing it with a generic cleanup status. Avoid broad catches that convert every throwable into a successful fallback value. The correct boundary reports what completed, what failed and what remains unknown.
Test initialization, body and closing independently
Build a fixture whose initialization, body and close behavior can each be selected independently. Test a normal body with one close failure, a failing body with two close failures, and a second-resource initialization failure after the first resource was acquired. Assert both the exception tree and the event sequence. A resource that never initialized must not appear in the close-attempt list.
Also test the all-success path and a null resource expression, which the language does not close. These cases reveal accidental assumptions in homegrown cleanup helpers. If the code exposes a diagnostic JSON format, round-trip the synthetic exception tree and verify that suppressed children retain their order and relationship. Do not count a serialization test as proof that real operating-system cleanup succeeded.
The companion fixture is intended to run with a local JDK and no third-party dependencies. The exact JDK version used by a validation run should be recorded in its results. The language rules are documented for Java SE 25, while the basic syntax used here is compatible with earlier modern JDKs. Compatibility claims for a particular deployment still require running its actual toolchain.
Migrate resource ownership one boundary at a time
Find manual cleanup blocks that manage resources implementing AutoCloseable. Convert one ownership boundary at a time and add the failure matrix before changing exception wrappers. Make it clear which scope owns closing each resource; closing a caller-owned object unexpectedly can be as harmful as leaking it. Resource declarations should reflect the lifetime of the work, not merely the shortest convenient syntax.
Finally inspect logging and monitoring downstream of the change. If a logger prints only getMessage, the application will still hide suppressed failures even though the runtime preserved them correctly. Verify one deliberately failing fixture through the complete reporting path. No agent is needed to decide cleanup order. Deterministic language semantics and a small set of explicit ownership rules provide a stronger foundation for the worker's failure report.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.