Java 8 CompletableFuture Handle Exception

Exception handling is important in software development, Java 8 CompletableFuture also provides methods to handle errors when they occurs.

Related article:
Java Future
Java 8 CompletableFuture
Java 8 Multiple CompletableFutures

I. Ways to handle exception
1. Using exceptionally method

For the example in previous post, we should use exceptionally() after chain of thenApply() methods:

Run the code, the result will be:

"not detected" is the String we return to future object before call the first thenApply() method.

2. Using handle method

Another way to handle exception is using handle method:

In the example, instead of using exceptionally, we can make a more flexible code like this

Run the code, the result will be:

II. Source code

In the example, we pass 3 as input parameter to make an error when calling numbers.get(index). The future object then bring a String "not detected".
Exception will occur when invoking thenApply(Integer::parseInt). So we catch exception using exceptionally/handle method.

Check results in Console Screen:


Related Posts



1 thought on “Java 8 CompletableFuture Handle Exception”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*