Sub topic 15
When close() Fails Too: Suppressed Exceptions
You already know that try-with-resources closes resources for you. But close() is a method like any other, and it can throw an exception too. So what happens when the body of the try block fails and then close() fails as well? That gives you two exceptions at once, and Java can only throw one of them.
This chapter shows how Java handles that case. You will learn what a suppressed exception is, how to read suppressed exceptions with getSuppressed(), and how they show up in a stack trace.
The Problem: Two Failures, One Throw
A method can only throw one exception at a time. When a second failure happens during cleanup, one of the two exceptions has to "win." The question is which one, and what happens to the other.
The old style of cleanup, with a finally block, gets this wrong. Look at this program:
public class LostExceptionDemo {
static class Resource {
void close() {
throw new IllegalStateException("close failed");
}
}
public static void main(String[] args) {
Resource r = new Resource();
try {
try {
throw new RuntimeException("body failed");
} finally {
r.close();
}
} catch (RuntimeException e) {
System.out.println("caught: " + e.getMessage());
}
}
}Output:
caught: close failedThe real problem was "body failed". That is the exception you need in order to fix the bug. But the exception thrown inside finally replaced it, and the first one is gone. Nothing printed it or saved it anywhere.
The Fix: Suppressed Exceptions
A suppressed exception is an exception that Java attaches to another exception instead of throwing it. The exception it is attached to is called the primary exception. The primary exception is the one that actually gets thrown and that your catch block receives.
try-with-resources uses this rule:
- If the body throws, that exception becomes the primary exception.
- Java then closes each resource. If a
close()call throws, Java does not throw that exception. It callsaddSuppressed()on the primary exception to attach it. - The primary exception is thrown, with every close failure stored inside it.
Nothing is lost. The main error stays on top, and the cleanup errors travel with it.
Seeing It in Action
Here is a resource whose close() always fails. Two of them are opened in one try-with-resources statement, and the body throws as well.
public class SuppressedDemo {
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
}
@Override
public void close() {
System.out.println("closing " + name);
throw new IllegalStateException("close failed: " + name);
}
}
public static void main(String[] args) {
try (Resource a = new Resource("a"); Resource b = new Resource("b")) {
throw new RuntimeException("body failed");
} catch (RuntimeException e) {
System.out.println("caught: " + e.getMessage());
for (Throwable s : e.getSuppressed()) {
System.out.println("suppressed: " + s.getMessage());
}
}
}
}Output:
closing b
closing a
caught: body failed
suppressed: close failed: b
suppressed: close failed: aHere is what happened, step by step:
- The body threw
"body failed". This became the primary exception. - Java closed
bfirst, because resources close in reverse order.b.close()threw, so Java attached that exception to the primary one. - Java still closed
a. One failedclose()does not stop the others from running.a.close()threw too, and that exception was attached as well. - The
catchblock received"body failed", the error that matters most. getSuppressed()returned an array of the two close failures, in the order they happened.
What If Only close() Fails?
If the body finishes without an error, there is no primary exception yet. In that case the first close() failure becomes the primary exception. Any later close failures are attached to it as suppressed.
public class CloseOnlyDemo {
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
}
@Override
public void close() {
System.out.println("closing " + name);
throw new IllegalStateException("close failed: " + name);
}
}
public static void main(String[] args) {
try (Resource a = new Resource("a"); Resource b = new Resource("b")) {
System.out.println("body ok");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
for (Throwable s : e.getSuppressed()) {
System.out.println("suppressed: " + s.getMessage());
}
}
}
}Output:
body ok
closing b
closing a
caught: close failed: b
suppressed: close failed: ab closes first, so its failure is primary. a's failure is attached to it.
| Body result | First close() result | Primary exception | Suppressed exceptions |
|---|---|---|---|
| Throws | Throws | Body exception | All close failures |
| Throws | Succeeds | Body exception | None (or later close failures) |
| Succeeds | Throws | First close failure | Later close failures |
| Succeeds | Succeeds | None | None |
Suppressed Exceptions in a Stack Trace
You do not always need to loop over getSuppressed(). When you call printStackTrace(), or when an uncaught exception ends your program, Java prints suppressed exceptions for you. Each one appears under a line that starts with Suppressed:. The output looks roughly like this:
java.lang.RuntimeException: body failed
at SuppressedDemo.main(SuppressedDemo.java:18)
Suppressed: java.lang.IllegalStateException: close failed: b
at SuppressedDemo$Resource.close(SuppressedDemo.java:12)
at SuppressedDemo.main(SuppressedDemo.java:17)
Suppressed: java.lang.IllegalStateException: close failed: a
at SuppressedDemo$Resource.close(SuppressedDemo.java:12)
at SuppressedDemo.main(SuppressedDemo.java:17)The top line is the primary exception. The indented Suppressed: blocks are the cleanup failures. Each has its own stack trace, so you can see which close() method failed.
Suppressed vs Cause
In the chapter on exception chaining you met the cause, which you set with new SomeException(message, cause) and read with getCause(). The two ideas are easy to mix up.
| Row | Cause | Suppressed |
|---|---|---|
| Meaning | "This error happened *because of* that one" | "This other error *also* happened" |
| How many | At most one | Any number |
| Set by | Constructor or `initCause()` | `addSuppressed()` |
| Read with | `getCause()` | `getSuppressed()` |
| Printed as | `Caused by:` | `Suppressed:` |
A cause explains why the error happened. Suppressed exceptions are separate failures that happened at about the same time.
Adding Suppressed Exceptions Yourself
addSuppressed() is a public method on Throwable, so you can use it in your own code. This is useful when you clean up several things by hand and want to report every failure.
import java.util.List;
public class ManualSuppressDemo {
public static void main(String[] args) {
List<String> tasks = List.of("ok", "bad1", "ok", "bad2");
RuntimeException first = null;
for (String task : tasks) {
try {
if (task.startsWith("bad")) {
throw new IllegalStateException("task failed: " + task);
}
} catch (RuntimeException e) {
if (first == null) {
first = e;
} else {
first.addSuppressed(e);
}
}
}
if (first != null) {
System.out.println("primary: " + first.getMessage());
for (Throwable s : first.getSuppressed()) {
System.out.println("suppressed: " + s.getMessage());
}
}
}
}Output:
primary: task failed: bad1
suppressed: task failed: bad2Exercises
Exercise
In LostExceptionDemo, the finally block's close() throws "close failed" after the try block threw "body failed". Which message does the catch block print, and what happens to the other exception?
Show answer
It prints "caught: close failed". The "body failed" exception is lost completely. It is not attached anywhere, because a plain finally block does not use suppressed exceptions.
Exercise
A try-with-resources statement opens resources x, then y, then z. The body runs without error. Then z.close() succeeds, y.close() throws "Y", and x.close() throws "X". What does the catch block receive, and what does getSuppressed() return?
Show answer
Resources close in the order z, y, x. Since the body succeeded, the first close failure, "Y", becomes the primary exception. "X" is attached to it, so getSuppressed() returns an array holding one exception with the message "X".
Exercise
You catch an exception and print only e.getMessage(). Why might you miss important information, and what should you do instead?
Show answer
getMessage() shows only the primary exception's message. It does not show suppressed exceptions or the cause. Print or log the whole exception, for example with e.printStackTrace(), so the "Suppressed:" and "Caused by:" sections appear too.