Java SE API
CompletableFuture.exceptionally()
Recover a failed stage using a replacement value.
Formal Syntax & Structure
java syntaxjava
CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fn | Function<Throwable, ? extends T> | Recovery function |
Working Example
Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static final class MissingPrice extends RuntimeException { private static final long serialVersionUID = 1L; } public static void main(String[] args) throws Exception { CompletableFuture<Integer> lookup = new CompletableFuture<>(); CompletableFuture<Integer> recovered = lookup.exceptionally(error -> { Throwable cause = error instanceof CompletionException ? error.getCause() : error; if (cause instanceof MissingPrice) return 50; throw new CompletionException(cause); }); lookup.completeExceptionally(new MissingPrice()); System.out.println(recovered.join()); System.out.println(lookup.isCompletedExceptionally()); }}