Java ExecutionException
Future.get wraps a failure from its computation in ExecutionException. Inspect getCause to identify the original failure.
A simple example
ExecutionException
- Start with A background task fails during conversion
- Do this Collect its result
- Result Wrapper holds the conversion failure
Syntax
job.get()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind 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.
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());
}
}
}
Invalid price
The failed future records the importer's original exception. The reporting screen retrieves its message from the cause.
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.
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");
}
}
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.
Code and output in Java
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");
}
}
}
Job complete
What to watch for
Future.get also allows interruption. Handle an interrupted caller according to the application's shutdown policy.