Ch. 7 · Java

Java CompletableFuture Error Composition

How exceptions travel through CompletableFuture chains, when to use exceptionally, handle or whenComplete, and why causes arrive wrapped.

~7 min readadvancedupdated Nov 1, 2026

A CompletableFuture pipeline calls three services and one of them throws. What does the caller see, and how do you return a fallback for just that call? Answering takes three pieces of knowledge: how a failure moves through dependent stages, which methods recover and which only observe, and why an instanceof check on the exception so often fails the first time.

Getting this wrong produces three recognisable bugs: an exception stored in a future that nobody reads, a fallback attached to the wrong stage so it masks unrelated failures, and a call that hangs forever because nothing set a timeout. The model below avoids all three. If you already chain supplyAsync, thenApply and thenCompose, you have the background; just remember that stages run on the executor you pass, or on the common ForkJoinPool if you pass none.

A failed stage skips ahead to the first handler

When a stage throws, its future completes exceptionally and every dependent thenApply, thenAccept or thenCompose is skipped; the failure flows downstream until a handler runs. exceptionally and handle can turn the failure into a normal value, while whenComplete only observes it and passes the original outcome on. Dependent stages usually see the exception wrapped in a CompletionException, so unwrap the cause before checking its type, and remember that join() rethrows it wrapped while get() wraps it in ExecutionException.

Skipped stages, the wrapping rule and three handler families

Every CompletableFuture holds either a result or an exceptional outcome. Each dependent stage registers a callback that runs when its source completes. Normal-path methods such as thenApply check the outcome first: if the source failed, they skip the function and complete their own future with the same failure. That is why one exception in the middle of a long chain jumps straight to the next handler.

CompletableFuture<Integer> f = CompletableFuture
        .supplyAsync(() -> { throw new IllegalStateException("db down"); })
        .thenApply(x -> (Integer) x + 1)          // skipped
        .thenApply(x -> x * 2)                    // skipped
        .exceptionally(ex -> {
            System.out.println(ex.getClass().getSimpleName()); // CompletionException
            System.out.println(ex.getCause().getMessage());    // db down
            return -1;
        });

System.out.println(f.join()); // -1
java

The wrapping rule: when a function inside a stage throws, the framework stores the exception wrapped in a CompletionException (unless it already is one). If you complete a future manually with completeExceptionally(new IOException()), or orTimeout fires, that future holds the raw exception. A handler attached directly to it receives the IOException itself, while a thenApply stage that depends on it fails with a CompletionException wrapping it, and handlers further down see that wrapper. Writing handlers that unwrap defensively covers both cases.

The three handler families differ in what they can do:

Method Sees Can recover Output
exceptionally(fn) failure only yes new value of same type
handle(fn) value or failure yes any type
whenComplete(action) value or failure no same outcome as source
exceptionallyCompose(fn) (Java 12+) failure only yes, asynchronously a future

Unwrap, recover, observe, combine

Step 1: Write an unwrap helper

static Throwable unwrap(Throwable t) {
    while ((t instanceof CompletionException || t instanceof ExecutionException)
            && t.getCause() != null) {
        t = t.getCause();
    }
    return t;
}
java

Use it in every handler that branches on exception type. Without it, ex instanceof TimeoutException can be false, because whether the handler sees the raw exception or a wrapper depends on where in the chain the failure started.

Step 2: Recover close to the call that can fail

Attach the fallback directly to the stage it protects so unrelated failures are not masked:

CompletableFuture<Price> price = pricingClient.fetch(sku)       // returns a future
        .orTimeout(300, TimeUnit.MILLISECONDS)                   // Java 9+
        .exceptionally(ex -> {
            Throwable cause = unwrap(ex);
            if (cause instanceof TimeoutException) {
                return Price.cached(sku);
            }
            throw new CompletionException(cause);              // rethrow others
        });
java

Rethrowing inside exceptionally keeps the stage failed. Wrapping in CompletionException avoids double wrapping and is legal for checked causes.

Step 3: Observe without changing the outcome

CompletableFuture<Order> order = placeOrder(cmd)
        .whenComplete((result, ex) -> {
            if (ex != null) {
                log.warn("order failed for {}", cmd.id(), unwrap(ex));
            } else {
                metrics.increment("orders.placed");
            }
        });
java

whenComplete returns a future with the same result or the same failure. If the action itself throws while the source succeeded, the returned future fails with the action’s exception; if the source had already failed, the original failure wins.

Step 4: Combine several futures

CompletableFuture<Price> p = fetchPrice(sku);
CompletableFuture<Stock> s = fetchStock(sku);

CompletableFuture<ProductView> view = p.thenCombine(s, ProductView::new)
        .handle((v, ex) -> ex == null ? v : ProductView.unavailable(sku));
java

thenCombine fails if either input fails. With CompletableFuture.allOf(a, b, c), the combined future fails once all inputs have completed and at least one of them failed; an early failure does not cancel the others. Collect per-input fallbacks before allOf if you want partial results.

Tests that pin wrapping, whenComplete and handle

import static org.junit.jupiter.api.Assertions.*;
import java.util.concurrent.*;
import org.junit.jupiter.api.Test;

class FutureErrorsTest {
    @Test
    void failureSkipsThenApplyAndIsWrapped() {
        var f = CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("x"); })
                .thenApply(v -> "never");
        var ex = assertThrows(CompletionException.class, f::join);
        assertInstanceOf(IllegalStateException.class, ex.getCause());
    }

    @Test
    void whenCompleteDoesNotRecover() {
        var f = CompletableFuture.<String>failedFuture(new RuntimeException("boom"))
                .whenComplete((v, e) -> {});
        assertTrue(f.isCompletedExceptionally());
    }

    @Test
    void handleRecovers() {
        var f = CompletableFuture.<String>failedFuture(new RuntimeException("boom"))
                .handle((v, e) -> e == null ? v : "fallback");
        assertEquals("fallback", f.join());
    }
}
java

Recommendations that vanish without a log line

Picture a product page that aggregates recommendations from a slow service. A first implementation often looks like this:

CompletableFuture<List<Item>> recs = CompletableFuture
        .supplyAsync(() -> recClient.load(userId))
        .thenApply(this::rank);

recs.thenAccept(items -> page.setRecommendations(items));
return page;
java

When recClient.load throws, thenAccept never runs and the exception is stored in a future nobody reads. There is no log and no fallback; the page silently renders without recommendations, and nothing tells anyone why. When the service hangs instead, the future never completes. Because the default executor is the common pool, which has one thread fewer than the machine has cores, a handful of hung calls also starve every other parallelStream and default-executor future in the JVM.

The fixed version adds a dedicated executor, a timeout, logging and an explicit fallback, and it joins the result before rendering:

private final ExecutorService recPool = Executors.newFixedThreadPool(16);

CompletableFuture<List<Item>> recs = CompletableFuture
        .supplyAsync(() -> recClient.load(userId), recPool)
        .thenApply(this::rank)
        .orTimeout(500, TimeUnit.MILLISECONDS)
        .exceptionally(ex -> {
            log.warn("recommendations unavailable for {}", userId, unwrap(ex));
            return List.of();
        });

page.setRecommendations(recs.join());
java

Note that orTimeout completes the future exceptionally but does not interrupt the thread running recClient.load. The HTTP client still needs its own timeout so the pool thread is released.

Handler mistakes that hide failures

  • Checking the type without unwrapping. ex instanceof IOException is usually false because ex is a CompletionException.
  • Expecting whenComplete to recover. It never changes a failure into a value. Use handle or exceptionally.
  • Placing exceptionally too late. A single handler at the end of a long chain catches every failure and may return a fallback for a bug that should have surfaced.
  • Believing cancel interrupts the task. CompletableFuture.cancel(true) completes the future with CancellationException; the mayInterruptIfRunning flag has no effect on the running code.
  • Fire-and-forget chains. A future that nobody joins or handles hides its failure completely.

get() vs join(), Java 8 timeouts and handler threads

What is the difference between get() and join()? get() throws checked ExecutionException and InterruptedException; join() throws unchecked CompletionException, which is friendlier inside lambdas.

How do you add a timeout on Java 8? There is no orTimeout before Java 9. Use a scheduled executor that calls completeExceptionally(new TimeoutException()), or race the future with applyToEither.

When would you use exceptionallyCompose? When recovery itself is asynchronous, for example retrying a call or falling back to a secondary service that returns a future.

Which thread runs a non-async handler? Either the thread that completed the source, or the calling thread if the source was already complete when the handler was attached. Use the ...Async variants with an executor if handlers do blocking work.

Try it: allOf with one early failure

You call allOf(a, b, c).join() and b fails after 50 ms while a and c take two seconds. When does join() throw, and how would you return as soon as any call fails?

The answer, with a fail-fast helper

allOf completes only when all inputs complete, so join() throws after about two seconds, with a CompletionException caused by b’s exception. The early failure does not short-circuit and does not cancel a or c. To fail fast, attach a handler to each input that completes a shared result future exceptionally on the first failure:

static CompletableFuture<Void> allOrFirstFailure(CompletableFuture<?>... fs) {
    CompletableFuture<Void> all = CompletableFuture.allOf(fs);
    for (CompletableFuture<?> f : fs) {
        f.whenComplete((v, ex) -> { if (ex != null) all.completeExceptionally(ex); });
    }
    return all;
}
java

completeExceptionally on the allOf future wins if it runs first, so the caller sees the failure after about 50 ms. You would still cancel or time out the remaining calls at the client level, because completing a future does not stop the work behind it.

Practise more concurrency questions in the Java interview questions and the Java MCQs. Related notes: executor shutdown and task lifecycle and virtual threads for blocking work. The complete method contract is in the CompletableFuture API documentation.

More in Java

esc