Library contents

Java ExecutionException

Future.get wraps a failure from its computation in ExecutionException. Inspect getCause to identify the original failure.

A simple example

ExecutionException

  1. Start with A background task fails during conversion
  2. Do this Collect its result
  3. Result Wrapper holds the conversion failure
Inspecting the cause shows what failed inside the task.

Syntax

Java syntax
job.get()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Find the reason a background import failed

A shop processes a price list in a background job. The job encounters an invalid price, and the reporting screen needs the original reason when it collects the result.

ResultInvalid price
Main.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

class Main {
    public static void main(String[] args) throws Exception {
        var job = CompletableFuture.<Integer>failedFuture(new IllegalArgumentException("Invalid price"));
        try {
            System.out.println(job.get());
        } catch (ExecutionException failed) {
            System.out.println(failed.getCause().getMessage());
        }
    }
}
Output
Invalid price

The failed future records the importer's original exception. The reporting screen retrieves its message from the cause.

Advertisements

Read a successful import result

A supplier corrects the malformed price row and the shop runs a fresh import. The reporting screen now receives the processed count from the completed job.

Result4 prices loaded
Main.java
import java.util.concurrent.CompletableFuture;

class Main {
    public static void main(String[] args) throws Exception {
        var importCount = CompletableFuture.completedFuture(4);
        System.out.println(importCount.get() + " prices loaded");
    }
}
Output
4 prices loaded

A normally completed future returns its value directly.

Collect a successful tally

A worker has finished adding attendance totals. Collect the worker result. When the background operation failed, mark the job for review.

GivenCompleted tally
Worked resultJob complete
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        try {
            CompletableFuture.completedFuture(18).get();
            System.out.println("Job complete");
        } catch (ExecutionException problem) {
            System.out.println("Review job");
        }
    }
}
Output
Job complete

What to watch for

Future.get also allows interruption. Handle an interrupted caller according to the application's shutdown policy.

Documentation for ExecutionException