gpt4 book ai didi

java-8 - Java 8 不同次要版本下 CompletionException 的不同消息

转载 作者:行者123 更新时间:2023-11-30 06:09:03 24 4
gpt4 key购买 nike

在不同的 java 次要版本下,我从相同的代码片段中得到了不同的输出。我在 open jdk bug tracker 上找不到相关的票证。

CompletableFuture<String> completableFuture = new CompletableFuture<>();
completableFuture.complete("xxx");

completableFuture.thenCompose(str -> {
CompletableFuture<String> completableFuture1 = new CompletableFuture<>();
completableFuture1.completeExceptionally(new Exception("hello"));
return completableFuture1;
}).exceptionally(ex -> {
System.out.println(ex.getMessage());
return null;
}).get();

JDK 1.8.0_25下的输出:

hello

JDK 1.8.0_102下的输出:

java.lang.Exception: hello

新版本是修复还是回归?相关票证是什么?

最佳答案

有一个错误报告 here讨论这一变化。关键在CompletableFuture#thenCompose的Javadoc中

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage as the argument to the supplied function. See the CompletionStage documentation for rules covering exceptional completion.

以及CompletionStage的类文档

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 CompletionException holding the exception as its cause.

这就是你在这里看到的。您传递给异常(exception)Function现在接收一个CompletionException,其中包含完成触发CompletableFuture<的Exception/.

您现在看到的行为是预期的行为。

您必须打开包装才能了解异常完成的原因

Throwable cause = ex.getCause(); // this is your Exception("Hello")

关于java-8 - Java 8 不同次要版本下 CompletionException 的不同消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38831877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com