CompletableFuture 和例外 - 这里缺少什么?

CompletableFuture and exceptionally - what is missing here?

当我试图理解 exceptionally 功能时,我阅读了一些 blogs and posts ,但我不明白这段代码有什么问题:

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

我以为我可以在使用 exceptionallyhandle 调用 divideByZero 方法时捕获异常,但程序只是打印堆栈跟踪并退出.

我都试过了,或者 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;
                }

            })

但结果总是:

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

当您调用 divideByZero() 时,代码 int x = 5 / 0; 运行 立即出现在调用者的线程中,这解释了为什么如您所描述的那样失败(异常甚至在CompletableFuture 对象被创建)。

如果你希望在以后的任务中被零除是运行,你可能需要将方法改成这样:

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

Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero 结尾(由 java.lang.ArithmeticException: / by zero 引起)