Skip to lesson

Suppressed exceptions

When the body of a try-with-resources throws and then close() throws too, Java keeps the body's exception as the main one and attaches the close failure to it as a suppressed exception. Nothing is lost, and the real cause stays on top.

An exception in the body and another in close

A suppressed exception is one thrown while closing a resource after another exception already happened; it is attached to the first one instead of replacing it.

A suppressed exception is an exception that Java attaches to another one instead of throwing it. In try-with-resources, if the body throws and then close() also throws, the body's exception is thrown, and the one from close() is added to it as suppressed.

The body throws IOException "read failed on marks-pendrive", then close() throws IOException "close failed on marks-pendrive". The catch block gets the body exception, and the close failure is attached to it as a suppressed exception, readable with getSuppressed().

Example 1 · The body's exception wins, the close failure is attached

SuppressedDemo.javaJava
import java.io.IOException;
class Usb implements AutoCloseable {    private final String name;    private final boolean closeFails;
    Usb(String name, boolean closeFails) {        this.name = name;        this.closeFails = closeFails;    }
    @Override    public void close() throws IOException {        if (closeFails) {            throw new IOException("close failed on " + name);        }        System.out.println("closed " + name);    }}
public class SuppressedDemo {    static void copyMarks(boolean bodyFails) throws IOException {        try (Usb usb = new Usb("marks-pendrive", true)) {            if (bodyFails) {                throw new IOException("read failed on marks-pendrive");            }            System.out.println("  copied marks");        }    }
    public static void main(String[] args) {        System.out.println("Case 1: body and close both fail");        try {            copyMarks(true);        } catch (IOException e) {            System.out.println("  caught: " + e.getMessage());            for (Throwable s : e.getSuppressed()) {                System.out.println("  suppressed: " + s.getMessage());            }        }
        System.out.println("Case 2: only close fails");        try {            copyMarks(false);        } catch (IOException e) {            System.out.println("  caught: " + e.getMessage());            System.out.println("  suppressed count: " + e.getSuppressed().length);        }    }}
Output
Case 1: body and close both fail
  caught: read failed on marks-pendrive
  suppressed: close failed on marks-pendrive
Case 2: only close fails
  copied marks
  caught: close failed on marks-pendrive
  suppressed count: 0

What this code does

  • In case 1, the caller catches the read failure. The close failure is not lost: it is in e.getSuppressed().
  • In case 2 the body works, so the close failure becomes the main exception and there is nothing suppressed.

The body's exception is usually the real problem: the read failed, the data was wrong. The close failure is often a result of it. So Java throws the cause and keeps the result attached for anyone who wants to look.

If the body runs fine and only close() throws, there is nothing to attach to. The close exception is thrown normally.

addSuppressed and getSuppressed

Every exception (every Throwable) has two methods for this, added in Java 7. addSuppressed(Throwable t) attaches t; try-with-resources calls it for you. getSuppressed() returns the attached exceptions as an array, in the order they were added, and an empty array when there are none.

Example 2 · Two close failures in one try

TwoSuppressedDemo.javaJava
import java.io.IOException;
class Usb implements AutoCloseable {    private final String name;    private final boolean closeFails;
    Usb(String name, boolean closeFails) {        this.name = name;        this.closeFails = closeFails;    }
    @Override    public void close() throws IOException {        if (closeFails) {            throw new IOException("close failed on " + name);        }        System.out.println("closed " + name);    }}
public class TwoSuppressedDemo {    public static void main(String[] args) {        try (Usb a = new Usb("drive A", true);             Usb b = new Usb("drive B", true);             Usb c = new Usb("drive C", false)) {            throw new IOException("backup of hostel records failed");        } catch (IOException e) {            System.out.println("caught: " + e.getMessage());            Throwable[] all = e.getSuppressed();            for (int i = 0; i < all.length; i++) {                System.out.println("suppressed[" + i + "]: " + all[i].getMessage());            }        }    }}
Output
closed drive C
caught: backup of hostel records failed
suppressed[0]: close failed on drive B
suppressed[1]: close failed on drive A

What this code does

  • Drive C closes fine. Drive B and drive A fail, in that order, because resources close last to first.
  • Each failure is added to the body's exception with addSuppressed, so getSuppressed() returns B's failure at index 0 and A's at index 1.

Example 3 · addSuppressed by hand: release every lock

CloseAllDemo.javaJava
import java.util.List;
class RoomLock {    private final String room;
    RoomLock(String room) {        this.room = room;    }
    void release() {        if (room.endsWith("jammed")) {            throw new IllegalStateException("cannot release " + room);        }        System.out.println("released " + room);    }}
public class CloseAllDemo {    static void releaseAll(List<RoomLock> locks) {        RuntimeException first = null;        for (RoomLock lock : locks) {            try {                lock.release();            } catch (RuntimeException e) {                if (first == null) {                    first = e;                    // the main error                } else {                    first.addSuppressed(e);       // keep the others too                }            }        }        if (first != null) {            throw first;        }    }
    public static void main(String[] args) {        List<RoomLock> locks = List.of(new RoomLock("A-101"), new RoomLock("A-102 jammed"),                new RoomLock("A-103"), new RoomLock("A-104 jammed"));        try {            releaseAll(locks);        } catch (IllegalStateException e) {            System.out.println("error: " + e.getMessage());            for (Throwable s : e.getSuppressed()) {                System.out.println("  also: " + s.getMessage());            }        }    }}
Output
released A-101
released A-103
error: cannot release A-102 jammed
  also: cannot release A-104 jammed

What this code does

  • releaseAll keeps going after a failure, so A-103 is still released. The first failure becomes the main error.
  • Every later failure is attached with first.addSuppressed(e), so the caller sees all jammed rooms, not only the first.
  • e.getSuppressed() returns Throwable[], never null.
  • e.addSuppressed(e) throws IllegalArgumentException: Self-suppression not permitted.
  • addSuppressed(null) throws NullPointerException.

With several resources, each failing close() adds one suppressed exception. Resources close last to first, so the last declared resource's failure comes first in the array. You can also call addSuppressed yourself, for example when you close many things in a loop and want to report every failure, not only the first.

The "Suppressed:" part of a stack trace

When an exception with suppressed exceptions is printed, each suppressed one shows up under it, indented one more step and labelled Suppressed:. Its own at lines follow, indented further.

Example 4 · A stack trace with a Suppressed: block

SuppressedTraceDemo.javaJava
import java.io.IOException;
class Usb implements AutoCloseable {    void read() throws IOException {        throw new IOException("read failed on marks-pendrive");    }
    @Override    public void close() throws IOException {        throw new IOException("close failed on marks-pendrive");    }}
public class SuppressedTraceDemo {    public static void main(String[] args) {        try (Usb usb = new Usb()) {            usb.read();        } catch (IOException e) {            e.printStackTrace(System.out);   // usually printed to System.err        }    }}
Output
java.io.IOException: read failed on marks-pendrive
	at Usb.read(SuppressedTraceDemo.java:5)
	at SuppressedTraceDemo.main(SuppressedTraceDemo.java:17)
	Suppressed: java.io.IOException: close failed on marks-pendrive
		at Usb.close(SuppressedTraceDemo.java:10)
		at SuppressedTraceDemo.main(SuppressedTraceDemo.java:16)

What this code does

  • The first line and its at lines are the main error: read() failed at line 5, called from main at line 17.
  • The indented Suppressed: block is the close failure. Its last at line points to line 16, the try line, because Java calls close() from code it generates for the try.

Read the top line first: that is the main error and where it happened. Then read each Suppressed: block: those are problems that happened while cleaning up. In logs from servers, the suppressed block often explains a strange second error, like a connection that could not close because the network was down.

How old finally code lost the main exception

In old try-finally code, an exception thrown from finally simply replaces the one that was leaving the try. If read() fails and then close() in finally fails, the caller sees only "close failed". The real cause, the read failure, is gone without a trace.

Example 5 · Old finally code versus try-with-resources

LostErrorDemo.javaJava
import java.io.IOException;
class Usb implements AutoCloseable {    private final String name;    private final boolean closeFails;
    Usb(String name, boolean closeFails) {        this.name = name;        this.closeFails = closeFails;    }
    @Override    public void close() throws IOException {        if (closeFails) {            throw new IOException("close failed on " + name);        }        System.out.println("closed " + name);    }}
public class LostErrorDemo {    static void oldStyle() throws IOException {        Usb usb = new Usb("marks-pendrive", true);        try {            throw new IOException("read failed on marks-pendrive");        } finally {            usb.close();                 // its exception replaces the read error        }    }
    static void newStyle() throws IOException {        try (Usb usb = new Usb("marks-pendrive", true)) {            throw new IOException("read failed on marks-pendrive");        }    }
    static void report(String label, IOException e) {        System.out.println(label + " caught: " + e.getMessage()                + " (suppressed: " + e.getSuppressed().length + ")");    }
    public static void main(String[] args) {        try {            oldStyle();        } catch (IOException e) {            report("finally:", e);        }        try {            newStyle();        } catch (IOException e) {            report("try-with-resources:", e);        }    }}
Output
finally: caught: close failed on marks-pendrive (suppressed: 0)
try-with-resources: caught: read failed on marks-pendrive (suppressed: 1)

What this code does

  • oldStyle loses the read failure: the caller only sees the exception from close() in finally, with nothing suppressed.
  • newStyle does the same work with try-with-resources. The caller sees the read failure, with the close failure kept as suppressed.

This made bugs hard to find: the log showed a close error, while the true problem was earlier. try-with-resources fixed it by design. Its generated code catches the close failure and calls addSuppressed on the main exception, so both are kept.

Next step

Check your understanding

12 quick questions