Exception Java8 CompletableFuture方法的惊人行为

Exception Java8 CompletableFuture方法的惊人行为,exception,java-8,completable-future,Exception,Java 8,Completable Future,我遇到了Java8 CompletableFuture.method的奇怪行为。如果我执行这段代码,它工作正常并打印java.lang.RuntimeException CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); future.exceptionally(e -> {

我遇到了Java8 CompletableFuture.method的奇怪行为。如果我执行这段代码,它工作正常并打印
java.lang.RuntimeException

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

future.completeExceptionally(new RuntimeException());

future.exceptionally(e -> {
            System.out.println(e.getClass());
            return null;
});
为什么会发生这种情况?在我看来,这相当令人惊讶。

这种行为:

方法还允许阶段计算替换结果,该替换结果可允许其他相关阶段进行进一步处理。在所有其他情况下,如果某个阶段的计算因(未检查的)异常或错误而突然终止,则要求其完成的所有相关阶段也会异常完成,并保留异常作为其原因


如果你认为你可能想知道你调用的那个阶段是否是异常的失败,或者它的直接或间接先决条件之一。

是的,行为是意料之中的,但是如果你想从原来的一个阶段中抛出的原始异常,你可以简单地使用这个

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

future.completeExceptionally(new RuntimeException());

future.thenApply(v-> v).exceptionally(e -> {
        System.out.println(e.getCause()); // returns a throwable back
        return null;
});
CompletableFuture=newcompletablefuture();
future.completeeexception(新的RuntimeException());
未来。然后应用(v->v)。例外情况下(e->{
System.out.println(e.getCause());//返回一个一次性返回
返回null;
});

请参阅,了解异常何时包装(或是否包装)的概述。我发现这篇文章有助于我更好地理解此问题的解决方案->@0bserver,您添加的链接提供了大量信息,并澄清了我的许多疑问,尽管不是全部:)很高兴我能在@NIGAGA提供一些帮助。
CompletableFuture<String> future = new CompletableFuture<>();

future.completeExceptionally(new RuntimeException());

future.thenApply(v-> v).exceptionally(e -> {
        System.out.println(e.getCause()); // returns a throwable back
        return null;
});