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

Error Handling: When Either Future Fails

Understand that if either CompletableFuture fails, the combined future completes exceptionally.

Error Handling: When Either Future Fails

What you'll learn: How thenCombine behaves when one or both of the combined CompletableFuture objects fail with an exception.

When you combine two independent futures with thenCombine, you're essentially creating a dependency: the combined future can only succeed if both input futures complete successfully. If either future fails, the entire combined operation fails.

How Failures Propagate

Think of it like assembling a product from two parts. If either part arrives damaged, you cannot complete the assembly — the whole task fails. Similarly, thenCombine waits for both futures to finish, but if either completes exceptionally, the combined future immediately completes exceptionally as well.

The exception from the failing future propagates to the combined future. If both futures fail, typically the first exception encountered is the one that surfaces (though this isn't guaranteed due to concurrent execution).

Practical Implications

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    return 10;
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Database error");
});

CompletableFuture<Integer> combined = future1.thenCombine(future2, 
    (result1, result2) -> result1 + result2);

// combined will complete exceptionally with RuntimeException

In this example, even though future1 completes successfully, the combined future fails because future2 throws an exception. The combining function never executes — there's no point trying to add results when one is missing.

This fail-fast behavior is crucial for building reliable async pipelines. You don't want partial success masking failures in dependent operations.

Key Takeaway: When using thenCombine, if either input CompletableFuture fails, the combined future completes exceptionally with that error, and the combining function is never invoked.