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

handle vs exceptionally: Key Differences

Understand when handle receives both value and exception, unlike exceptionally which only handles errors.

handle vs exceptionally: Key Differences

You'll learn: How handle differs from exceptionally by receiving both the successful result and any exception, giving you unified error handling in one place.

The Core Difference

While exceptionally only gets called when something goes wrong (receiving just the exception), handle is always called regardless of success or failure. It receives two parameters: the result value (if successful) and the exception (if failed). Exactly one of these will be non-null.

Think of it like a universal receiver at a sorting facility: handle always gets the package, whether it's intact or damaged. Meanwhile, exceptionally is like a returns department that only sees broken items.

When Each Parameter is Non-Null

CompletableFuture.supplyAsync(() -> "Success")
    .handle((result, exception) -> {
        // result = "Success", exception = null
        return result.toUpperCase();
    });

CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Oops");
})
    .handle((result, exception) -> {
        // result = null, exception = RuntimeException
        return "Recovered";
    });

Why This Matters

With handle, you can inspect both paths in a single method:

.handle((value, ex) -> {
    if (ex != null) {
        return "Error: " + ex.getMessage();
    }
    return "Success: " + value;
})

This is impossible with exceptionally, which only sees failures and can't access the success value.

Choosing Between Them

Use exceptionally when you only care about error cases and want to provide fallbacks. Use handle when you need conditional logic that considers both success and failure, or when you want unified post-processing regardless of outcome.

Key Takeaway: handle receives both result and exception (one always null), making it suitable for unified handling of all outcomes, while exceptionally only handles error paths with no access to successful results.