riorio
riorio

Reputation: 6816

CompletableFuture and exceptionally - what is missing here?

As I try to understand the exceptionally functionality, I read several blogs and posts , but I don't understand what is wrong with this code:

 public CompletableFuture<String> divideByZero(){
    int x = 5 / 0;
    return CompletableFuture.completedFuture("hi there");
}

I thought that I will be able to catch the exception when calling the divideByZero method with the exceptionally or the handle, but the program simply prints the stack trace and exits.

I tried both or handle & exceptionally:

            divideByZero()
            .thenAccept(x -> System.out.println(x))
            .handle((result, ex) -> {
                if (null != ex) {
                    ex.printStackTrace();
                    return "excepion";
                } else {
                    System.out.println("OK");
                    return result;
                }

            })

But the result is always:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Upvotes: 1

Views: 372

Answers (1)

ernest_k
ernest_k

Reputation: 45319

When you call divideByZero(), the code int x = 5 / 0; runs immediately in the caller's thread, which explains why it's failing as you describe (the exception is being raised even before a CompletableFuture object gets created).

If you want the division by zero to be run in the future's task, you may need to change the method to something like this:

public static CompletableFuture<String> divideByZero() {
    return CompletableFuture.supplyAsync(() -> {
        int x = 5 / 0;
        return "hi there";
    });
}

Which ends with Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero (caused by java.lang.ArithmeticException: / by zero)

Upvotes: 1

Related Questions