When an exception is thrown inside a CompletableFuture stage, how does it propagate down the chain? What is CompletionException and where does it come from?
answer
- Throw -> stage completes exceptionally -> normal stages skipped
- Dependent stages wrap cause in CompletionException
- Raw only when failed explicitly
- Always unwrap via getCause() in handlers
- CompletionException is unchecked
basics
~10 sIf a stage throws, the future completes exceptionally and later stages are skipped until an error-handling callback. The original exception is usually wrapped in a CompletionException, so you often unwrap it via getCause().
solid answer
~40 sWhen the function inside a stage throws, that stage completes exceptionally, and the JDK's CompletableFuture stores the throwable wrapped in an unchecked CompletionException. Downstream dependent stages (thenApply, thenCompose, etc.) are then skipped: each completes exceptionally with that same CompletionException until the first error-aware callback (exceptionally/handle/whenComplete). So the Throwable a handler receives is usually a CompletionException whose getCause() is your real exception. The raw exception shows up where code fails a future directly: completeExceptionally(ex), failedFuture(ex) and obtrudeException(ex) store ex itself and cancel() a bare CancellationException; a handler attached directly to that future sees it unwrapped, and every stage after it sees it wrapped. That is why robust handlers unwrap: if (ex instanceof CompletionException) ex = ex.getCause(). join() throws the same CompletionException, so the wrapping is consistent across propagation and the blocking accessor.
code
java · 8 linesCompletableFuture.supplyAsync(() -> { throw new IllegalArgumentException("bad"); })
.thenApply(v -> v + "!") // skipped on failure
.exceptionally(ex -> {
Throwable cause = (ex instanceof CompletionException)
? ex.getCause() : ex; // unwrap before inspecting
System.out.println(cause.getClass()); // IllegalArgumentException
return "fallback";
});go deeper
Knows that a thrown exception makes the future 'fail' and that later steps don't run; may not mention wrapping.
Explains short-circuit propagation past normal stages and that the cause is wrapped in CompletionException, so handlers unwrap via getCause().
Knows a thrown exception is stored wrapped even at the stage that threw it, that a future failed directly (completeExceptionally, failedFuture, obtrudeException, cancel) holds it raw, the no-double-wrap rule, and writes unwrap-normalizing handlers.
Designs a consistent exception-normalization layer (helper to unwrap), reasons about cancellation vs failure surfacing, and standardizes error semantics across an async codebase.
## The model A `CompletableFuture` stage holds a function. When you run that function and it throws, the stage doesn't crash the program — it captures the `Throwable` and becomes **exceptionally completed**. The whole point of `CompletableFuture` is composition, so the interesting question is: what happens to the *chain* of stages built on top of a failing one? ## Short-circuit propagation Dependent stages created with `thenApply`, `thenAccept`, `thenCompose`, `thenCombine`, etc. only run on **normal** completion of their input. If the input completed exceptionally, these stages are **skipped** and *also* complete exceptionally with the same failure. The error therefore "short-circuits" past all the normal-path stages until it reaches an error-aware stage: `exceptionally`, `handle`, or `whenComplete`. This is analogous to an exception unwinding past statements until a `catch`. ```java cf.thenApply(this::step1) // skipped if cf failed .thenApply(this::step2) // skipped .exceptionally(ex -> { // <-- first to actually run on failure // ex may be a CompletionException wrapping the real cause return fallback(); }); ``` ## What is CompletionException? `CompletionException` is an **unchecked** (`RuntimeException`) wrapper, added in Java 8 with `CompletableFuture`. The `CompletionStage` contract says that when a stage's computation throws, **all dependent stages** requiring it complete exceptionally **with a `CompletionException` holding the exception as its cause**. The JDK's `CompletableFuture` wraps even earlier: the stage whose function threw already stores the wrapper, and dependents relay that same object. A cause that is already a `CompletionException` is not wrapped again. So: - A stage whose function **threw** (a `supplyAsync` supplier, a `thenApply` function) holds `CompletionException(cause = IllegalStateException)`, and a handler attached **directly** to it already sees the wrapper. - A future failed **explicitly** with `completeExceptionally(ex)`, `failedFuture(ex)` or `obtrudeException(ex)` holds `ex` itself, and a cancelled one holds a bare `CancellationException`, so a handler attached directly to it sees the exception raw. - Every stage **downstream** of either one inherits the failure as a `CompletionException`. Why wrap at all? The Javadoc's own reason is that the convention **distinguishes exceptions in an action itself from those it depends on**; to treat them alike, catch `RuntimeException` and inspect `getCause()`. It also gives `join()` one unchecked type to throw for any failure other than cancellation, including a checked exception a producer passed to `completeExceptionally`, since the functional interfaces the callbacks implement cannot declare checked exceptions. `ExecutionException` plays the analogous role for `get()`. ## Practical consequence: always unwrap Because whether you see the wrapper depends on how the future failed (a thrown exception, or a direct failure such as `completeExceptionally`) and where the handler sits, robust handlers normalize: ```java future.exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException && ex.getCause() != null) ? ex.getCause() : ex; if (cause instanceof TimeoutException) { return cachedValue(); } return fallback(); }); ``` If you skip the unwrap, an `instanceof` check against your domain exception may silently fail because you're actually holding a `CompletionException`. ## Edge cases - If the thrown exception is already a `CompletionException`, it is **not** re-wrapped. - `whenComplete` and `handle` receive the same (possibly wrapped) throwable that propagated to them. - Cancellation: `join()` and `get()` on the cancelled future itself throw `CancellationException`, not a `CompletionException` or `ExecutionException`. A stage downstream of a cancelled future fails with a `CompletionException` whose cause is the `CancellationException`, so there `join()` throws `CompletionException` and `get()` throws `ExecutionException`. ## Mental model Think of the failure as a letter in an envelope. When an action throws, the JDK seals the letter in a `CompletionException` envelope at once, and every later stage passes that same envelope along. Only a letter handed over directly, by `completeExceptionally`, `failedFuture`, `obtrudeException` or `cancel`, starts unsealed, and the first stage that relays it seals it. Open the envelope (`getCause()`) before reading the letter.
- Does CompletableFuture ever double-wrap into CompletionException(CompletionException(...))?No. If the propagating cause is already a CompletionException, it is not wrapped again; the existing CompletionException is reused.
- Why must this wrapper be unchecked?CompletableFuture's callbacks are functional interfaces that cannot declare checked exceptions, so any failure (including checked ones) must be carried by an unchecked RuntimeException: CompletionException, or CancellationException for a cancellation.
- Doing instanceof on the domain exception without unwrapping CompletionException first
- Believing a stage whose own function threw holds the raw exception (it already holds a CompletionException)
- Thinking downstream thenApply stages still run after a failure
- Confusing CompletionException (propagation/join) with ExecutionException (get)
- CompletionException
- Java 1.8
context
- CompletionStage (Java SE 27 & JDK 27)docs.oracle.com
- CompletableFuture (Java SE 27 & JDK 27)docs.oracle.com
- CompletableFuture.java at jdk-27-gagithub.com