Sub topic 8
Handling errors: exceptionally, handle, whenComplete
This chapter assumes you know Java 8 lambdas, Function, Consumer and Supplier, and the difference between checked and unchecked exceptions. You should also have seen supplyAsync, thenApply and join from earlier chapters.
How a failure travels through a chain
A CompletableFuture stage finishes in one of two ways: with a value or with an exception. If a stage fails, every dependent stage that was waiting on it fails too. Their functions are skipped, and each dependent completes exceptionally with the same failure.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class Propagation {
static int load() {
throw new IllegalStateException("db down");
}
public static void main(String[] args) {
CompletableFuture<String> chain = CompletableFuture
.supplyAsync(Propagation::load)
.thenApply(n -> {
System.out.println("never printed");
return n * 2;
})
.thenApply(n -> "value " + n);
try {
chain.join();
} catch (CompletionException e) {
System.out.println("join threw: " + e.getCause());
}
System.out.println(chain.isCompletedExceptionally());
}
}This prints join threw: java.lang.IllegalStateException: db down and then true. Neither thenApply function ran.
Exception wrapping
Java wraps failures in a CompletionException when they pass from one stage to a dependent stage. It also wraps an exception thrown inside supplyAsync or runAsync. As a result, your handler often receives a CompletionException whose getCause() is the exception you actually threw.
How the failure reaches the caller depends on the retrieval method.
| Retrieval | What you see for a failed future |
|---|---|
| `join()` | Unchecked `CompletionException` with the original exception as its cause |
| `get()` | Checked `ExecutionException` with the original exception as its cause |
| `exceptionally`, `handle`, `whenComplete` | The raw exception if you completed that very future with `completeExceptionally`, otherwise usually a `CompletionException` |
Because of this uncertainty, write a small unwrapping helper and use it in every handler.
static Throwable unwrap(Throwable t) {
return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t;
}exceptionally: recover from a failure
exceptionally(Function<Throwable, T> fn) runs only if the stage failed. It returns a replacement value of the same type T. If the stage succeeded, the value passes through unchanged.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class Recover {
static Throwable unwrap(Throwable t) {
return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t;
}
public static void main(String[] args) {
CompletableFuture<Integer> port = CompletableFuture
.supplyAsync(() -> Integer.parseInt("80x"))
.exceptionally(ex -> {
System.out.println("cause: " + unwrap(ex).getClass().getSimpleName());
return 8080;
});
System.out.println(port.join());
}
}The output is cause: NumberFormatException followed by 8080.
Where you place exceptionally matters. It only sees failures from stages above it. A failure in a stage added below it is not caught.
CompletableFuture<Integer> f = CompletableFuture
.supplyAsync(() -> Integer.parseInt("x"))
.exceptionally(ex -> 0) // recovers the parse failure
.thenApply(n -> 10 / n); // ArithmeticException: not recoveredHere f.join() throws a CompletionException caused by ArithmeticException. If you want to cover the whole chain, put the handler at the end. If you want to recover partway and continue, put it in the middle.
You can also fail with a better exception by throwing from the handler. A thrown exception becomes the stage's failure.
.exceptionally(ex -> {
throw new IllegalStateException("config unavailable", unwrap(ex));
})handle: one function for both outcomes
handle(BiFunction<T, Throwable, U> fn) always runs. Exactly one of its two arguments is non-null: the value on success, the exception on failure. It returns a new value, so it can convert either outcome into a result. The result type U may differ from T.
import java.util.concurrent.CompletableFuture;
public class HandleDemo {
public static void main(String[] args) {
CompletableFuture<Integer> parsed = CompletableFuture
.supplyAsync(() -> Integer.parseInt("abc"))
.handle((value, ex) -> {
if (ex != null) {
System.out.println("failed: " + ex);
return -1;
}
return value;
});
System.out.println(parsed.join());
}
}It prints failed: java.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "abc" and then -1.
Always test ex != null before you use it. A successful stage passes null for ex, and calling a method on it throws NullPointerException inside your handler. That exception then becomes the stage's failure and hides the original result.
A related trap is a null value. A successful stage can legitimately produce null, so test ex, not value, to tell the outcomes apart.
whenComplete: observe without changing the outcome
whenComplete(BiConsumer<T, Throwable> action) also runs on both outcomes, but it returns nothing. The new stage has the same outcome as the original. Use it for logging, metrics and cleanup.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class Observe {
static Throwable unwrap(Throwable t) {
return (t instanceof CompletionException && t.getCause() != null) ? t.getCause() : t;
}
static String fetch(boolean fail) {
if (fail) {
throw new IllegalArgumentException("bad id");
}
return "profile";
}
public static void main(String[] args) {
for (boolean fail : new boolean[] {false, true}) {
String result = CompletableFuture
.supplyAsync(() -> fetch(fail))
.whenComplete((v, ex) -> System.out.println(
"log: value=" + v + ", error="
+ (ex == null ? "none" : unwrap(ex).getMessage())))
.handle((v, ex) -> ex == null ? v : "anonymous")
.join();
System.out.println(result);
}
}
}The output is:
log: value=profile, error=none
profile
log: value=null, error=bad id
anonymouswhenComplete logged the failure but did not stop it. The handle stage after it did the recovery.
Two details govern what happens when the action itself throws:
- If the original stage succeeded and the action throws, the new stage fails with the action's exception.
- If the original stage had already failed, the original exception is kept. An exception from the action is added to it as a suppressed exception only if the original is not the same object.
Choosing between the three
| Method | Runs when | Can change the result | Typical use |
|---|---|---|---|
| `exceptionally` | Failure only | Yes, to a value of the same type | Fallback default |
| `handle` | Success or failure | Yes, to any type | Convert both outcomes into one result, such as a response object |
| `whenComplete` | Success or failure | No | Logging, metrics, releasing resources |
A common pattern combines them. Put whenComplete early for logging, then handle or exceptionally last for the final fallback.
Recovering with another asynchronous call
exceptionally must return a plain value. To recover by starting another asynchronous call, such as querying a backup service, you need exceptionallyCompose. It was added in Java 12.
CompletableFuture<String> data = primary()
.exceptionallyCompose(ex -> backup());On Java 8 to 11 you can get the same effect with handle followed by thenCompose, but it is clumsy. One approach is to make handle return a CompletableFuture<String> and flatten with thenCompose(f -> f).
Errors across many futures
When you combine futures, one failure affects the whole group.
allOfcompletes exceptionally if any input fails, but only after all inputs have finished. TheCompletionExceptionit produces carries one failure as its cause. To see every outcome, inspect each future individually, for example withisCompletedExceptionally().anyOfcompletes with whichever input finishes first, and that can be a failure even if other inputs would have succeeded.thenCombinefails if either input fails.
If you want partial results, attach a handle or exceptionally to each individual future before combining them. Each future then always succeeds, and allOf gives you a complete list.
Cancellation
Calling cancel(true) on a future completes it exceptionally with a CancellationException. A handler attached directly to that future sees the CancellationException itself, while dependent stages see it wrapped in a CompletionException. join() throws CancellationException directly for a cancelled future. Cancelling does not interrupt a thread that is already running the task, so the work may continue in the background.
Common mistakes
- Checking
value == nullinstead ofex != nullinsidehandle. - Placing
exceptionallybefore the stage that fails, so it never sees the error. - Comparing
ex.getClass()to your exception type without unwrapping theCompletionExceptionfirst, so the check never matches. - Expecting
whenCompleteto supply a fallback value. - Using
get()and forgetting to handle bothInterruptedExceptionandExecutionException.
Exercise
A chain is supplyAsync(() -> Integer.parseInt("x")).whenComplete((v, ex) -> log(ex)).thenApply(n -> n + 1). What does join() do, and what would you add so it returns 0 instead?
Show answer
join() throws a CompletionException whose cause is NumberFormatException. whenComplete only logs and does not recover, so the failure passes through, and the thenApply function is skipped. Add .exceptionally(ex -> 0) or .handle((v, ex) -> ex == null ? v : 0) at the end of the chain.
Exercise
In handle((v, ex) -> ...), a stage that failed with new IOException("net") inside supplyAsync gives ex. What is ex.getClass() and how do you reach the IOException?
Show answer
ex is a CompletionException, because the exception thrown inside supplyAsync is wrapped. Call ex.getCause() to reach the IOException, or use an unwrap helper that does this only when ex is a CompletionException.