exceptionally Position in the Chain
You'll learn: How the placement of exceptionally in a CompletableFuture pipeline determines which stages are protected and which can still process results after error recovery.
The Core Idea
The position of exceptionally in your pipeline matters significantly. It acts as a firewall that catches exceptions from all upstream stages but allows downstream stages to continue normally with the recovered value. Think of it like a circuit breaker in an electrical system—it protects everything before it, and everything after it operates on clean, recovered values.
How Position Affects Behavior
When you place exceptionally early in the chain, only stages before it are protected. Stages after it receive the fallback value as if nothing went wrong:
CompletableFuture.supplyAsync(() -> riskyOperation())
.exceptionally(ex -> "fallback") // Catches errors from supplyAsync
.thenApply(String::toUpperCase) // Always executes with valid string
.thenAccept(System.out::println); // Always receives a result
But if you place it at the end, all intermediate stages must succeed for the pipeline to reach it:
CompletableFuture.supplyAsync(() -> "data")
.thenApply(s -> riskyTransform(s)) // Not protected
.thenApply(s -> anotherTransform(s)) // Not protected
.exceptionally(ex -> "fallback"); // Only catches if above stages fail
Strategic Placement
Place exceptionally immediately after risky operations you want to recover from, and before stages that should always execute. You can even use multiple exceptionally calls at different points to handle different failure scenarios with different fallback strategies.
Key Takeaway: The position of exceptionally determines which upstream stages it protects and ensures all downstream stages receive valid values, transforming exception paths back into normal execution flows.