Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ExecutionException — task failure when retrieving a result

ExecutionException is a checked exception thrown when retrieving the result of a task that terminated with an exception. It separates task failure from the code receiving the result; getCause() lets you inspect the underlying cause.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

try { task.get(); } catch (ExecutionException e) { Throwable cause = e.getCause(); }

ExecutionException in java.util.concurrent extends Exception and is checked: you must catch it or declare it in throws. When retrieving a result through Future.get(), it signals that the computation terminated with an exception rather than a successful result.

Call getCause() to inspect the cause; do not identify it by parsing the text of getMessage(). The public constructors are ExecutionException(Throwable cause) and ExecutionException(String message, Throwable cause). A manually constructed instance can have a null cause, so general-purpose code should account for that.

Distinguish task failure from other outcomes of Future.get(): InterruptedException means the calling thread was interrupted while waiting, whereas CancellationException means the task was cancelled. The timed overload can additionally throw TimeoutException; expiration of that timeout alone does not mean the task failed or was cancelled.

In the example, FutureTask.run() executes the task on the current thread and records its failure. Only task.get() throws ExecutionException, with IllegalArgumentException as its cause. No additional thread or delays are needed. The example prints the cause's type and message; in production code, preserve the cause chain when propagating the failure.

Examples

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        FutureTask<Integer> task = new FutureTask<>(() -> {
            throw new IllegalArgumentException("invalid input");
        });
        task.run();

        try {
            task.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            System.out.println(e.getClass().getSimpleName());
            System.out.println(cause.getClass().getSimpleName() + ": " + cause.getMessage());
        }
    }
}

Result

ExecutionException
IllegalArgumentException: invalid input

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources