DEV Community

loading...

Java 8 CompletableFuture Handle Exception

loizenai profile image loizenai ・1 min read

https://grokonez.com/java/java-8/java-8-completablefuture-handle-exception

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:

I. Ways to handle exception

1. Using exceptionally method


CompletableFuture exceptionally()

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


future = future.thenApply(Integer::parseInt) // input String: "not detected"
                .thenApply(r -> r * 2 * Math.PI)
                .thenApply(s -> "apply>> " + s)
                .exceptionally(ex -> "Error: " + ex.getMessage());

Run the code, the result will be:


Error: java.lang.NumberFormatException: For input string: "not detected"

"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:

https://grokonez.com/java/java-8/java-8-completablefuture-handle-exception

Java 8 CompletableFuture Handle Exception

Discussion (0)

pic
Editor guide