Skip to content

io7m/jdeferthrow

Repository files navigation

jdeferthrow

Maven Central Maven Central (snapshot) Codecov

com.io7m.jdeferthrow

JVM Platform Status
OpenJDK (Temurin) Current Linux Build (OpenJDK (Temurin) Current, Linux)
OpenJDK (Temurin) LTS Linux Build (OpenJDK (Temurin) LTS, Linux)
OpenJDK (Temurin) Current Windows Build (OpenJDK (Temurin) Current, Windows)
OpenJDK (Temurin) LTS Windows Build (OpenJDK (Temurin) LTS, Windows)

The jdeferthrow package implements a trivial API for combining multiple exceptions over a series of statements.

Usage

final var tracker = new ExceptionTracker<IOException>();

try {
  doIO1();
} catch (IOException e1) {
  tracker.addException(e1);
}

try {
  doIO2();
} catch (IOException e2) {
  tracker.addException(e2);
}

try {
  doIO3();
} catch (IOException e3) {
  tracker.addException(e3);
}

tracker.throwIfNecessary();

The above code will execute doIO1, doIO2, and doIO3, catching each exception if any are raised. The throwIfNecessary method will throw whichever of e1, e2, or e3 was caught first, with either of the other two exceptions added to the thrown exception as a suppressed exception.

Concretely, if all of doIO1, doIO2, and doIO3 throw exceptions, the throwIfNecessary method will throw e1 with e2 and e3 added to e1 as suppressed exceptions.

This effectively allows for accumulating exceptions over a range of statements and then throwing an exception at the end that contains all of the exceptions that were thrown.

If addException was not called, throwIfNecessary does nothing.