Java - Retrieve suppressed exceptions via getSuppressed() method in Throwable class.

Introduction

getSuppressed() method of the Throwable class returns an array of Throwable objects.

Each object in the array represents a suppressed exception.

The following snippet of code demonstrates the use of the getSuppressed() method to retrieve the suppressed exceptions:

Demo

class MyResource implements AutoCloseable {
  private int level;
  private boolean exceptionOnClose;

  public MyResource(int level, boolean exceptionOnClose) {
    this.level = level;
    this.exceptionOnClose = exceptionOnClose;
    System.out.println("Creating MyResource. Level = " + level);
  }//from w ww.jav a2s  . c  o m

  public void use() {
    if (level <= 0) {
      throw new RuntimeException("Low in level.");
    }
    System.out.println("Using MyResource level " + this.level);
    level--;
  }

  @Override
  public void close() {
    if (exceptionOnClose) {
      throw new RuntimeException("Error in closing");
    }
    System.out.println("Closing MyResource...");
  }
}

public class Main {
  public static void main(String[] args) {
    try (MyResource mr = new MyResource(2, true)) {
      mr.use();
      mr.use();
      mr.use(); // Throws an exception
    } catch (Exception e) {
      System.out.println(e.getMessage());

      // Display messages of suppressed exceptions
      System.out.println("Suppressed exception messages are...");
      for (Throwable t : e.getSuppressed()) {
        System.out.println(t.getMessage());
      }
    }

  }
}

Result

Related Topic