CompletableFuture already completed with an exception

五迷三道 提交于 2019-11-26 17:49:01

问题


CompletableFuture.completedFuture() returns a CompletedFuture that is already completed with the given value.

How do we construct a CompletableFuture that is already completed exceptionally?

Meaning, instead of returning a value I want the future to throw an exception.


回答1:


Unlike Java 9 and later, Java 8 does not provide a static factory method for this scenario. The default constructor can be used instead:

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



回答2:


Java 9 provides CompletableFuture.failedFuture​(Throwable ex) that does exactly that.



来源:https://stackoverflow.com/questions/49116855/completablefuture-already-completed-with-an-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!