首页 > 解决方案 > CompletableFuture 和异常 - 这里缺少什么?

问题描述

当我尝试理解该exceptionally功能时,我阅读了几篇博客帖子,但我不明白这段代码有什么问题:

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

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

我尝试了两个或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;
                }

            })

但结果总是:

线程“主”java.lang.ArithmeticException 中的异常:/ 为零

标签: javaexceptionjava-8completable-future

解决方案


当您调用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)结尾


推荐阅读