【问题标题】:CompletableFuture and exceptionally - what is missing here?CompletableFuture 和异常 - 这里缺少什么?
【发布时间】:2019-10-25 19:21:05
【问题描述】:

当我试图理解 exceptionally 功能时,我阅读了几个 blogsposts ,但我不明白这段代码有什么问题:

 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;
                }

            })

但结果总是:

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

【问题讨论】:

  • 如果可能抛出异常,你的这个块必须在 try catch 中 public CompletableFuture divideByZero(){ int x = 5 / 0; return CompletableFuture.completedFuture("你好"); }

标签: java exception java-8 completable-future


【解决方案1】:

当您调用 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引起)

【讨论】:

    猜你喜欢
    • 2016-04-11
    • 2020-09-21
    • 2010-12-24
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2015-12-24
    相关资源
    最近更新 更多