简体   繁体   English

CompletableFuture已完成,但有异常

[英]CompletableFuture already completed with an exception

CompletableFuture.completedFuture() returns a CompletedFuture that is already completed with the given value. CompletableFuture.completedFuture()返回使用给定值完成的CompletedFuture

How do we construct a CompletableFuture that is already completed exceptionally? 我们如何构造一个已经异常完成的CompletableFuture

Meaning, instead of returning a value I want the future to throw an exception. 意思是,我不希望返回一个值,而希望返回一个异常。

Unlike Java 9 and later, Java 8 does not provide a static factory method for this scenario. 与Java 9和更高版本不同,Java 8在这种情况下不提供静态工厂方法。 The default constructor can be used instead: 可以使用默认构造函数代替:

CompletableFuture<T> future = new CompletableFuture<>();
future.completeExceptionally(exception);

Java 9提供了CompletableFuture.failedFuture​(Throwable ex)来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM