Java : ExecutionException with Examples

ExecutionException (Java SE 23 & JDK 23) in Java with Examples.
You will find code samples for most of the ExecutionException methods.


Summary

Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.

Class diagram

try (final var executor = Executors.newSingleThreadExecutor()) {
    final var future = executor.submit(() -> {
        System.out.println("task : start");
        throw new IllegalStateException("task error!");
    });
    future.get();
} catch (ExecutionException e) {
    System.out.println("ExecutionException! : " + e.getCause());
}

// Result
// ↓
//task : start
//ExecutionException! : java.lang.IllegalStateException: task error!

Constructors

ExecutionException ()

Constructs an ExecutionException with no detail message.

protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.

ExecutionException (String message)

Constructs an ExecutionException with the specified detail message.

protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.

ExecutionException (String message, Throwable cause)

Constructs an ExecutionException with the specified detail message and cause.

final var cause = new IOException("XYZ");
final var e = new ExecutionException("abcd", cause);

System.out.println(e); // java.util.concurrent.ExecutionException: abcd
System.out.println(e.getMessage()); // abcd

System.out.println(e.getCause()); // java.io.IOException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

ExecutionException (Throwable cause)

Constructs an ExecutionException with the specified cause.

final var cause = new IOException("XYZ");
final var e = new ExecutionException(cause);

// java.util.concurrent.ExecutionException: java.io.IOException: XYZ
System.out.println(e);

System.out.println(e.getCause()); // java.io.IOException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page