Course contentsShow
← Java
Lesson 2838 of 2,87051. CompletableFutureFree lesson

exceptionally as a Catch Block in the Pipeline

How exceptionally acts like a catch block, only executing when an upstream exception occurs.

exceptionally as a Catch Block in the Pipeline

You'll learn how exceptionally works like a traditional try-catch block, activating only when an exception occurs upstream in your CompletableFuture chain.

The Core Concept

Think of exceptionally as a safety net positioned along your async pipeline. Just like a catch block in synchronous code only runs when an exception is thrown from the try block, exceptionally only executes when an upstream stage in your CompletableFuture chain completes exceptionally.

If all upstream operations succeed, exceptionally is completely skipped—your result flows through unchanged. The function you provide to exceptionally never gets called unless something goes wrong.

How It Behaves

CompletableFuture.supplyAsync(() -> {
    return 10 / 0;  // ArithmeticException!
})
.thenApply(result -> result * 2)  // This never runs
.exceptionally(ex -> {
    // This DOES run - catches the exception
    System.out.println("Caught: " + ex.getMessage());
    return -1;  // Provide fallback value
});

In the example above, the division by zero triggers an exception. The thenApply stage never executes because the pipeline is already in an error state. The exceptionally handler catches the exception and provides a recovery value.

The Synchronous Analogy

// Traditional synchronous code:
try {
    int result = 10 / 0;
    result = result * 2;  // Never runs
} catch (Exception ex) {  // Runs only on exception
    System.out.println("Caught: " + ex.getMessage());
    result = -1;
}

Key Takeaway: exceptionally acts as your pipeline's catch block—it only executes when an upstream exception occurs, letting you handle errors and provide fallback values while keeping successful results untouched.