Exceptions in thenApply Functions
What you'll learn: How exceptions thrown inside thenApply propagate and complete the resulting CompletableFuture exceptionally.
When you chain transformations with thenApply, you're working with a pipeline where data flows from stage to stage. But what happens when something goes wrong inside your transformation function?
How Exception Propagation Works
If the function you pass to thenApply throws an exception (either a checked exception wrapped in a runtime exception, or an unchecked exception), that exception doesn't crash your program. Instead, it completes the resulting CompletableFuture exceptionally.
Think of it like a factory assembly line: if one station encounters a problem, the product doesn't just disappear—it gets flagged as defective and sent to a different handling area. Similarly, your exception flows through the pipeline as a "failed" result.
What Happens to the Chain
Once an exception occurs in thenApply:
- The resulting
CompletableFuturecompletes exceptionally with that exception - Subsequent
thenApplystages in the chain are skipped - The exception can be retrieved using
get()(wrapped inExecutionException) orjoin()(wrapped inCompletionException)
Example
CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> "42")
.thenApply(s -> Integer.parseInt(s))
.thenApply(n -> {
if (n > 40) {
throw new IllegalArgumentException("Too large!");
}
return n * 2;
})
.thenApply(n -> n + 10); // This stage is skipped!
// result.join() throws CompletionException caused by IllegalArgumentException
Key Takeaway: Exceptions thrown inside thenApply functions don't terminate your program—they complete the resulting CompletableFuture exceptionally, skip subsequent transformations, and can be handled later in the pipeline.