Processing Exceptions with handle
What you'll learn: How to use the throwable parameter in handle's BiFunction to detect and recover from exceptions in your CompletableFuture pipeline.
The Throwable Parameter
The handle method receives a BiFunction<T, Throwable, U> where the second parameter is crucial for exception processing. When your pipeline completes normally, this Throwable parameter is null. When an exception occurs anywhere upstream, it contains the exception object.
This design lets you inspect what went wrong and make intelligent recovery decisions based on the specific failure.
Checking for Exceptions
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Random failure");
}
return 42;
}).handle((result, throwable) -> {
if (throwable != null) {
System.err.println("Caught exception: " + throwable.getMessage());
return 0; // Default value
}
return result;
});
The pattern is simple: check if throwable != null. If it is non-null, you're in the error path.
Type-Specific Recovery
You can inspect the exception type to provide tailored recovery:
.handle((result, throwable) -> {
if (throwable != null) {
if (throwable instanceof TimeoutException) {
return -1; // Timeout default
} else if (throwable instanceof IllegalArgumentException) {
return -2; // Validation failure
}
return 0; // Generic failure
}
return result * 2; // Process successful result
});
This is like having both a try-catch with multiple catch blocks and a success path in one construct.
Why This Matters
Unlike exceptionally, which only sees failures, handle gives you the exception object itself—not just notification that something failed. You can log detailed messages, extract error codes, or make recovery decisions based on exception types.
Key Takeaway: The throwable parameter in handle lets you detect exceptions with != null checks and implement type-specific recovery strategies based on the actual exception encountered.