加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

令人惊讶的行为Java 8 CompletableFuture异常的方法

发布时间:2020-12-14 16:30:40 所属栏目:Java 来源:网络整理
导读:我遇到了奇怪的行为 Java 8 CompletableFuture.exceptionally方法.如果我执行这个代码,它可以正常工作并打印出java.lang.RuntimeException CompletableFutureString future = new CompletableFuture();future.completeExceptionally(new RuntimeException())
我遇到了奇怪的行为 Java 8 CompletableFuture.exceptionally方法.如果我执行这个代码,它可以正常工作并打印出java.lang.RuntimeException
CompletableFuture<String> future = new CompletableFuture<>();

future.completeExceptionally(new RuntimeException());

future.exceptionally(e -> {
            System.out.println(e.getClass());
            return null;
});

但是如果我在未来的处理中添加了另一个步骤,那么就将异常类型更改为java.util.concurrent.CompletionException,原始异常包含在里面.

CompletableFuture<String> future = new CompletableFuture<>();

future.completeExceptionally(new RuntimeException());

future.thenApply(v-> v).exceptionally(e -> {
            System.out.println(e);
            return null;
});

有什么理由要这样发生吗?在我看来,这是非常令人惊讶的.

解决方法

这个行为 is specified in the class documentation of CompletionStage (fourth bullet):

Method 07001 additionally allows the stage to compute a replacement result that may enable further processing by other dependent stages. In all other cases,if a stage’s computation terminates abruptly with an (unchecked) exception or error,then all dependent stages requiring its completion complete exceptionally as well,with a 07002 holding the exception as its cause.

如果您认为您可能想知道您是否特别引用的舞台失败或其中一个直接或间接的先决条件,这并不奇怪.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读