Suppressed Exceptions in Java: Explanation & Practice

Handle exceptions during close()

Problem summary

When close() throws an exception, it gets suppressed. Access and print suppressed exceptions.

Starter code

class Resource implements AutoCloseable {
    public void use() throws Exception {
        throw new Exception("Error during use");
    }
    
    @Override
    public void close() throws Exception {
        throw new Exception("Error during close");
    }
}

public class Main {
    public static void main(String[] args) {
        try (Resource r = new Resource()) {
            r.use();
        } catch (Exception e) {
            System.out.println("Primary: " + e.getMessage());
            for (Throwable t : e.getSuppressed()) {
                System.out.println("Suppressed: " + t.getMessage());
            }
        }
    }
}

Expected output and test cases

  • Suppressed exception accessed
    Primary: Error during use
    Suppressed: Error during close

Hints

  1. Primary exception is from try block
  2. close() exception is suppressed
  3. Use getSuppressed() to access them

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler