Handle errors: exceptionally, handle and whenComplete
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Async code fails just like normal code: a server is down, a PNR is wrong, a UPI limit is crossed. In a CompletableFuture pipeline there is no try around the steps, so you attach error handlers to the chain instead.
How an exception skips later steps
A future that completes exceptionally ends with an error instead of a value. The steps after it are skipped until a handler such as exceptionally or handle deals with the error.
When a step throws, its future completes exceptionally: it holds an error instead of a value. Every later thenApply, thenAccept, thenCompose and thenRun is skipped, and the error travels down the chain to the end.
Example 1 · One failed step skips all the rest
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;
public class SkippedStepsDemo { public static void main(String[] args) { CompletableFuture<String> chain = CompletableFuture .supplyAsync(() -> "PNR123") .thenApply(pnr -> { System.out.println("Step 1: validating " + pnr); if (pnr.length() != 10) { throw new IllegalArgumentException("PNR must have 10 digits"); } return pnr; }) .thenApply(pnr -> { System.out.println("Step 2: fetching status"); return "CNF"; }) .thenApply(status -> { System.out.println("Step 3: formatting"); return "Status: " + status; });
try { System.out.println(chain.join()); } catch (CompletionException e) { System.out.println("Failed: " + e.getCause().getMessage()); } System.out.println("Completed exceptionally? " + chain.isCompletedExceptionally()); }}Step 1: validating PNR123 Failed: PNR must have 10 digits Completed exceptionally? true
What this code does
- Step 1 throws, so steps 2 and 3 never print. The error is passed down the chain unchanged.
join()at the end throws aCompletionExceptionwhose cause is the originalIllegalArgumentException.
This works like a try block: after a throw, the remaining lines are skipped until a catch. In a pipeline the "catch" is an error handler such as exceptionally. With no handler, the error reaches join(), which throws it as a CompletionException. isCompletedExceptionally() tells you whether a future ended with an error.
exceptionally for a fallback value
exceptionally(fn) runs only when the stage before it failed. fn receives the error and returns a fallback value of the same type, so the chain continues as if that value had been the result.
Example 2 · exceptionally: a fallback when the score feed is down
import java.util.List;import java.util.concurrent.CompletableFuture;
public class ScoreFallbackDemo { static String liveScore(String match) { if (match.equals("IND vs AUS")) { return "IND 287/4 (45.2 ov)"; } throw new IllegalStateException("score feed down for " + match); }
public static void main(String[] args) { for (String match : List.of("IND vs AUS", "CSK vs MI")) { String shown = CompletableFuture.supplyAsync(() -> liveScore(match)) .exceptionally(ex -> "Score unavailable, refresh in a minute") .join(); System.out.println(match + ": " + shown); } }}IND vs AUS: IND 287/4 (45.2 ov) CSK vs MI: Score unavailable, refresh in a minute
What this code does
- For the first match there is no error, so
exceptionallypasses the real score through and its lambda never runs. - For the second match
liveScorethrows, andexceptionallyreturns aStringfallback, the same type as the score.join()then has a value to return and throws nothing.
Example 3 · Where you put exceptionally changes the result
import java.util.concurrent.CompletableFuture;
public class FallbackPositionDemo { static int fetchFare() { throw new IllegalStateException("fare server down"); }
public static void main(String[] args) { String early = CompletableFuture.supplyAsync(() -> fetchFare()) .exceptionally(ex -> 1400) // last known fare .thenApply(fare -> fare + 40) // convenience fee .thenApply(total -> "Pay Rs " + total) .join(); System.out.println("Fallback early: " + early);
String late = CompletableFuture.supplyAsync(() -> fetchFare()) .thenApply(fare -> fare + 40) .thenApply(total -> "Pay Rs " + total) .exceptionally(ex -> "Fare not available, try again") .join(); System.out.println("Fallback late: " + late); }}Fallback early: Pay Rs 1440 Fallback late: Fare not available, try again
What this code does
- Early: the fallback 1400 replaces only the fare, so the fee and formatting steps still run on it.
- Late: the two
thenApplysteps are skipped, and the fallback replaces the finalStringresult.
When there is no error, the value passes through untouched and fn never runs.
Where you put it matters. In the middle of a chain it replaces one missing value, and the later steps run with the fallback. At the end it replaces the whole result.
Trace the code
Follow an error down the chain
Variables
- fare
- not done yet
Output
(nothing printed yet)Line 5fare is an empty future: no fare has arrived, so nothing can run yet.
handle for result or error
handle((result, ex) -> ...) always runs, on success and on failure. It receives both: on success ex is null, on failure result is null. Whatever it returns becomes the new value, and the type may change.
Example 4 · handle: one status line for success or failure
import java.util.concurrent.CompletableFuture;
public class UpiStatusDemo { static String pay(int amount) { if (amount > 100000) { throw new IllegalArgumentException("UPI limit is Rs 1,00,000 per payment"); } return "TXN-" + amount; }
public static void main(String[] args) { for (int amount : new int[] {500, 250000}) { String status = CompletableFuture.supplyAsync(() -> pay(amount)) .handle((txn, ex) -> ex == null ? "SUCCESS " + txn : "FAILED: " + ex.getCause().getMessage()) .join(); System.out.println("Rs " + amount + " -> " + status); } }}Rs 500 -> SUCCESS TXN-500 Rs 250000 -> FAILED: UPI limit is Rs 1,00,000 per payment
What this code does
handleruns both times. On successexisnullandtxnholds the id; on failuretxnisnullandexholds the error.- The error arrives wrapped in a
CompletionException(see the last section), soex.getCause()gives the real message.
Use it when both outcomes become one kind of answer, such as a status line for the user: "SUCCESS ..." or "FAILED ...". exceptionally is a shortcut for the failure half of handle.
whenComplete and CompletionException wrapping
whenComplete((result, ex) -> ...) always runs and sees both, like handle, but it cannot change the outcome: the same value or the same error passes on. It is for side jobs such as logging and counting failures.
static Throwable unwrap(Throwable ex) { if (ex instanceof CompletionException && ex.getCause() != null) { return ex.getCause(); } return ex;}Handlers often receive a CompletionException instead of the error you threw. If the error came from a supplyAsync task or an earlier step, Java wraps it; if someone called completeExceptionally(e) on this very future, the handler gets e itself. The real error is then ex.getCause().
Example 5 · whenComplete logs without changing the result
import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;
public class ResultLogDemo { static int marksOf(String roll) { if (roll.startsWith("99")) { throw new IllegalArgumentException("no student " + roll); } return 85; }
static Throwable unwrap(Throwable ex) { if (ex instanceof CompletionException && ex.getCause() != null) { return ex.getCause(); } return ex; }
public static void main(String[] args) { for (String roll : List.of("21CS042", "99XX000")) { int marks = CompletableFuture.supplyAsync(() -> marksOf(roll)) .whenComplete((m, ex) -> { if (ex == null) { System.out.println("[log] " + roll + " ok: " + m); } else { System.out.println("[log] " + roll + " failed: " + unwrap(ex)); } }) .exceptionally(ex -> -1) .join(); System.out.println(roll + " -> " + marks); } }}[log] 21CS042 ok: 85 21CS042 -> 85 [log] 99XX000 failed: java.lang.IllegalArgumentException: no student 99XX000 99XX000 -> -1
What this code does
whenCompleteonly looks: the value 85, or the error, passes on to the next step unchanged. That is whyexceptionallyis still needed for the -1 fallback.unwrap(ex)removes theCompletionExceptionlayer, so the log shows the realIllegalArgumentException.
Example 6 · When the error is wrapped and when it is not
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;
public class WrappingDemo { static Throwable unwrap(Throwable ex) { if (ex instanceof CompletionException && ex.getCause() != null) { return ex.getCause(); } return ex; }
public static void main(String[] args) { CompletableFuture<Integer> fromTask = CompletableFuture.supplyAsync(() -> { throw new IllegalStateException("bank down"); }); CompletableFuture<Integer> direct = new CompletableFuture<>(); direct.completeExceptionally(new IllegalStateException("bank down")); CompletableFuture<Integer> oneStepLater = direct.thenApply(x -> x + 1);
System.out.println("from supplyAsync: " + fromTask.handle((r, ex) -> ex.getClass().getSimpleName()).join()); System.out.println("completed directly: " + direct.handle((r, ex) -> ex.getClass().getSimpleName()).join()); System.out.println("one step later: " + oneStepLater.handle((r, ex) -> ex.getClass().getSimpleName()).join()); System.out.println("after unwrap: " + fromTask.handle((r, ex) -> unwrap(ex).getClass().getSimpleName()).join()); }}from supplyAsync: CompletionException completed directly: IllegalStateException one step later: CompletionException after unwrap: IllegalStateException
What this code does
- An error thrown inside
supplyAsyncis stored wrapped.completeExceptionally(e)storeseas it is, so a handler on that same future gets the plainIllegalStateException; onethenApplylater it is wrapped again. - Because both cases happen, always unwrap before checking
instanceofor reading the message; the helper is safe for both.
So unwrap before you check the error type or show its message. A small helper keeps this in one place.
exceptionally: failure only; returns a fallback of the same type.handle: always; sees result and error; returns any type.whenComplete: always; sees result and error; result unchanged.
Next step
Check your understanding
12 quick questions