skip to content

CompletableFuture Exception Handling

exceptionally recovers, handle sees both outcomes, whenComplete observes without changing the result, and failures travel down the chain wrapped in CompletionException. The join-versus-get distinction (unchecked versus checked) is a routine follow-up.

part ofJavaread it →
on this pageshow

questions

5

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?

level: middleimportance: must knowfreq 60%

answer

  1. Throw -> stage completes exceptionally -> normal stages skipped
  2. Dependent stages wrap cause in CompletionException
  3. Raw only when failed explicitly
  4. Always unwrap via getCause() in handlers
  5. CompletionException is unchecked

basics

~10 s

If 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 s

When 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 lines
java
CompletableFuture.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

for a junior

Knows that a thrown exception makes the future 'fail' and that later steps don't run; may not mention wrapping.

for a middle

Explains short-circuit propagation past normal stages and that the cause is wrapped in CompletionException, so handlers unwrap via getCause().

for a senior

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.

for a principal

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

open as a page

Compare exceptionally, handle, and whenComplete on CompletableFuture. When would you reach for each, and how do they differ in what they receive and what they produce?

level: middleimportance: must knowfreq 72%

basics

~20 s

exceptionally runs only on failure and supplies a fallback value. handle runs on both success and failure and returns a new value. whenComplete runs on both for a side-effect (like logging) but is not designed to change the result.

open as a page

What is exceptionallyCompose and how does it differ from exceptionally? When is it the right tool?

level: seniorimportance: should knowfreq 38%

basics

~20 s

exceptionally returns a plain fallback value on error. exceptionallyCompose returns a whole new CompletableFuture on error — so the fallback can itself be asynchronous, like calling a backup service. It is the error-path version of thenCompose.

open as a page

When you block on a CompletableFuture that failed, how do join() and get() differ in the exception they throw? Why does that distinction exist?

level: seniorimportance: should knowfreq 55%

basics

~10 s

get() throws the checked ExecutionException (and you must catch it), while join() throws the unchecked CompletionException. Both wrap the real cause, so you call getCause() to reach it. join() is friendlier in lambdas.

open as a page

On which thread does a CompletableFuture exception-handling callback run, and what subtle bugs arise from that plus from where you place handle/whenComplete in the chain?

level: principalimportance: should knowfreq 30%

basics

~20 s

A non-async callback usually runs on whichever thread completed the stage (often a shared pool thread), so heavy or blocking work there can starve the pool. Where you put handle/whenComplete also matters: it only sees failures from stages above it, not below.

open as a page