Skip to main content
CompletableFuture · Topic 5 of 6

Handling errors

Definition​

If a step in a chain fails, the exception travels down the chain and later steps are skipped. exceptionally supplies a fallback value. handle runs whether the step succeeded or failed. join throws the failure wrapped in a CompletionException.

Example code​

A fallback value and a handle step

import java.util.concurrent.CompletableFuture;

class Demo {
public static void main(String[] args) {
CompletableFuture<Integer> failing = CompletableFuture.supplyAsync(() -> {
if (true) throw new IllegalStateException("service is down");
return 1;
});

int fallback = failing.exceptionally(error -> -1).join(); // only runs on failure
System.out.println("fallback: " + fallback);

String text = failing.handle((value, error) -> // runs in both cases
error == null ? "ok: " + value : "failed: " + error.getCause().getMessage()).join();
System.out.println(text);

try {
failing.join();
} catch (java.util.concurrent.CompletionException e) {
System.out.println("join threw: " + e.getCause());
}
}
}

// Output:
// fallback: -1
// failed: service is down
// join threw: java.lang.IllegalStateException: service is down

Finished this page? Track your progress (saved only in your browser).