In writing code with CompletableFuture, exception handling has a significant role to play. IncompleteFuture provides three methods for handling them: handle(), whenComplete(), and exceptionally(). You can easily get lost if you have no experience with APIs because they look so similar. The following section explains the differences between them and helps you determine which is the best option for your situation. My goal is to describe each API in detail, then compare their usage, and finally provide some examples where each API is most useful. Though the info is written in Java 11, the concepts should still be familiar in Java 8. Let's begin.
handle:
By passing the result and the exception of the current complete future to method handle(), you can transform the current result to another result or retrieve the exception.
Given "Oops" as an exception, we can use handle() to handle the result and exception, either recovering from the exception or returning the message directly.
The result is not available in the method exceptionally(). You have access to the exception instead. Since the method is named specifically for handling exceptions, this method is meant to handle only those cases. The logic in "exceptionally" will be skipped if the completable future was achieved successfully.
We can make use of exceptionally to recover from failure when a failed future returns an exception "Oops".
This result will be contained in the complete future cf1:
The next example shows how a command is skipped during execution. The future returns OK when it is successful. The logic won't be executed when adding another stage for handling the exception. If the complete future is CF1, it will simply return the same value as CF0.
otherFunction
or around the call tootherFunction()
)?