Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Compare exceptionally, handle and whenComplete for error handling in a CompletableFuture chain. What exceptions do join() and get() throw?

exceptionally(fn) runs only when the previous stage failed and returns a replacement value, so the chain recovers. handle((value, ex) -> ...) runs on both success and failure and turns either into a new value. whenComplete((value, ex) -> ...) also runs on both, but it is for side effects like logging and passes the original result on unchanged. join() throws the unchecked CompletionException and get() throws the checked ExecutionException, and both wrap the real cause. Java 12 added exceptionallyCompose for recovering with another async call.

Background to this question

Error handling is where CompletableFuture code most often goes wrong: failures get swallowed, logged twice, or reported as a wrapper exception with no useful message. Knowing the three error methods and the two ways of waiting is the foundation for writing chains that fail cleanly. In this answer, we will see how a failure travels through a chain, then look at exceptionally, handle and whenComplete one at a time with their results, compare what join() and get() throw, and finish with exceptionallyCompose.

1How a Failure Travels Through a Chain

When a stage throws an exception, its future completes exceptionally, meaning it holds an exception instead of a value. Every stage after it that expects a value, such as thenApply or thenAccept, is skipped and completes exceptionally with the same failure. So the failure travels down the chain until it meets a stage that handles errors.

Along the way, the exception is usually wrapped in a CompletionException, a RuntimeException that CompletableFuture uses to carry a failure from one stage to the next. The real exception is its cause. Our error handlers therefore often receive the wrapper, and we should look at getCause() before deciding what happened.

Java
CompletableFuture<Integer> f = CompletableFuture
.supplyAsync(() -> { throw new IllegalStateException("price service down"); })
.thenApply(x -> x * 2); // skipped
f.isCompletedExceptionally(); // true

2Exceptionally: Recover With a Replacement Value

exceptionally takes a function from the exception to a value of the same type. It runs only if the previous stage failed. On success it is skipped and the value passes through unchanged. On failure its return value becomes the result, so the chain continues as if nothing had gone wrong.

Java
CompletableFuture<Integer> price = CompletableFuture
.supplyAsync(() -> pricing.price(id)) // throws: service down
.exceptionally(ex -> {
log.warn("price fallback", ex.getCause()); // ex is a CompletionException here
return 0;
});
price.join(); // 0
CompletableFuture.supplyAsync(() -> 42).exceptionally(ex -> 0).join(); // 42, handler not called

Notice that the handler must return a value of the stage's type. We use exceptionally when we have a sensible default, such as an empty list or a cached value.

3Handle: Turn Either Outcome Into a New Value

handle takes a function of two arguments, the value and the exception. Exactly one of them is non-null: on success ex is null, on failure value is null. Whatever we return becomes the new result, and its type can differ from the original.

Java
CompletableFuture<String> label = CompletableFuture
.supplyAsync(() -> pricing.price(id))
.handle((value, ex) -> ex == null
? "Price: " + value // success: "Price: 1999"
: "Price unavailable"); // failure: "Price unavailable"
label.join();

So handle is the most general of the three. It is a good fit when we want to map both outcomes into one result type, for example a Result object, or when the success path also needs adjusting.

4WhenComplete: Observe Without Changing the Result

whenComplete also receives the value and the exception, but its action returns nothing. The stage it returns completes with exactly the same outcome as the previous one: the same value on success, the same failure on failure. It is meant for side effects such as logging, metrics or releasing a resource.

Java
CompletableFuture<Integer> logged = CompletableFuture
.supplyAsync(() -> pricing.price(id))
.whenComplete((value, ex) -> {
if (ex != null) log.error("price failed", ex.getCause());
else metrics.record("price.ok");
});
logged.join(); // on failure still throws CompletionException: nothing was recovered
The three error methods side by side
MethodRuns onResult of the new stage
exceptionally(ex -> v)failure onlyreplacement value v; success passes through
handle((v, ex) -> r)success and failurewhatever the function returns
whenComplete((v, ex) -> {})success and failurethe original value or failure, unchanged
exceptionallyCompose(ex -> stage)failure only (Java 12+)the result of another async stage

Notice that whenComplete does not recover the chain. If we want a fallback value, we need exceptionally or handle. There is one catch: if the action itself throws and the original stage had succeeded, the returned stage fails with the action's exception.

5What join() and get() Throw

Both methods wait for the future and return its value. They differ in how they report a failure. join() throws CompletionException, which is unchecked, so it fits nicely in lambdas and streams. get() throws ExecutionException, which is checked, so the compiler forces us to handle it, and it also throws InterruptedException because the waiting can be interrupted. In both cases, the real exception is the cause.

Java
CompletableFuture<Integer> failed = CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("down"); });
try { failed.join(); }
catch (CompletionException e) { e.getCause(); } // IllegalStateException: down
try { failed.get(); }
catch (ExecutionException e) { e.getCause(); } // IllegalStateException: down
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
// A cancelled future is the exception: both throw CancellationException directly

So whichever we use, we unwrap with getCause() before logging or checking the type. A log line that shows only CompletionException tells us almost nothing.

6ExceptionallyCompose: Recover With Another Async Call

Sometimes the fallback is itself asynchronous, for example asking a secondary service when the primary fails. exceptionally would give us a nested future in that case, the same problem thenApply has with async functions. Java 12 added exceptionallyCompose, which takes a function returning a CompletionStage and flattens it, just as thenCompose does for success.

Java
CompletableFuture<Integer> price = primary.priceAsync(id)
.exceptionallyCompose(ex -> secondary.priceAsync(id)); // CompletableFuture<Integer>, not nested
price.join(); // price from the secondary when the primary fails

Java 12 also added exceptionallyAsync, which runs the recovery function on another executor.

7Follow-up questions

If I put exceptionally in the middle of a chain, does it handle failures after it?

No. A handler only sees failures from the stages before it. A stage added after the handler can fail and the failure will travel past it. Put the recovery after the stages it should cover, or add a final handler at the end of the chain.

Is the exception passed to exceptionally always a CompletionException?

Usually, when the failure came from an earlier stage or from supplyAsync, it is wrapped. If we attach the handler directly to a future that someone completed with completeExceptionally(new IOException()), it receives the IOException itself. So the safe habit is to unwrap: if ex is a CompletionException with a cause, use the cause.

Which should I use at the end of a request, join or get?

In code that already handles checked exceptions, get with a timeout, get(2, SECONDS), is convenient. In lambdas and streams, join reads better. Either way, unwrap the cause, and prefer a timeout on the future itself, such as orTimeout, so nobody waits forever.

8Conclusion

In this answer, we saw that a failure skips every value stage until it meets a handler. exceptionally runs only on failure and returns a replacement value, handle runs on both outcomes and maps either into a new value, and whenComplete runs on both for side effects while leaving the result unchanged. join() throws the unchecked CompletionException and get() the checked ExecutionException, both wrapping the real cause, and Java 12's exceptionallyCompose lets us recover with another async call without nesting.

What to say in the interviewAbout 80 seconds aloud

Open with

The three differ in when they run and whether they change the result. exceptionally runs only if the previous stage failed; it gets the exception and returns a replacement value of the same type, so the chain recovers, and on success it is simply skipped. handle runs on both success and failure; it gets the value and the exception, exactly one of them non-null, and whatever it returns becomes the new result, which can even be a different type. whenComplete also runs on both, but it is only for side effects like logging or metrics; it returns nothing and the next stage sees the original value or the original failure, so it does not recover anything.

Then, if they want more

For waiting, join throws an unchecked CompletionException and get throws a checked ExecutionException plus InterruptedException. Both wrap the real exception as the cause, so I always unwrap with getCause before logging or checking the type, and a cancelled future throws CancellationException directly. One more detail: handlers only see failures from stages before them.

And since Java 12 there is exceptionallyCompose, which lets me recover with another async call, for example a secondary service, without ending up with a nested future.

About this answer

Last updated
12 November 2026
Versions it names
Java 12
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare exceptionally, handle and whenComplete for error handling in a CompletableFuture...": https://scrivio-interview-library.netlify.app/java/completable-future/196adc2980/