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

The Function Parameter: Throwable to Result

Understanding the Function<Throwable, T> parameter and how to inspect the exception type.

The Function Parameter: Throwable to Result

You'll learn how the exceptionally() method uses a Function<Throwable, T> to convert exceptions into fallback results.

Understanding the Function Signature

When you call exceptionally(), you provide a function that takes a Throwable as input and returns a value of your result type T. This parameter gives you direct access to the exception that occurred in your async pipeline:

CompletableFuture<String> future = supplyAsync(() -> {
    throw new IllegalStateException("Something broke");
})
.exceptionally(ex -> {
    // ex is the Throwable that was thrown
    return "fallback value";
});

Inspecting the Exception

The Throwable parameter lets you examine what went wrong and decide how to respond. You can check the exception type, read its message, or even log it:

CompletableFuture<Integer> result = supplyAsync(() -> {
    return 100 / 0;  // ArithmeticException
})
.exceptionally(ex -> {
    if (ex instanceof ArithmeticException) {
        return 0;  // Safe default for division errors
    }
    return -1;  // Different default for other errors
});

The Recovery Contract

Think of this function as your "exception translator." It receives the bad news (the Throwable) and must convert it into good news (a valid result of type T). The pipeline continues normally with whatever value you return, allowing downstream stages like thenApply() or thenAccept() to proceed.

supplyAsync(() -> fetchUserAge())
    .exceptionally(ex -> 18)  // Default age on error
    .thenAccept(age -> System.out.println("Age: " + age));

Key Takeaway: The Function<Throwable, T> parameter in exceptionally() gives you the thrown exception as input, allowing you to inspect its type and details before returning a recovery value that matches your pipeline's expected result type.