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:

By grokonez | December 14, 2016.

Last updated on July 1, 2017.

Related Posts

4 thoughts on “Java 8 CompletableFuture Handle Exception”

  1. How to propagate a checked exception(Let’s say ManagerException) all the way to the API layer where I have return logic to convert this ManagerException and render to JSON. I have return special logic to convert it into JSON because in Play framework, whenever I throw RuntimeException it creates response in HTML form(which play renderers it through it custom handler).

    So my basic question is how to propogate exception to the API layer. I say this because when I throw Runtime exception from let’s say thenApplyAsync(), I am unable to catch this exception in my API layer.(The thrown exception just gets displayed in an ugly manner in Postman in HTML format

  2. Please provide the real time scenario by using CompletableFuture and Future.

    So we can able to understand the actual difference between CompletableFuture and Future.

Got Something To Say:

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