24

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.

2
  • In which context do you need to do that? I think in a lot of contexts, just throwing the exception would do the job (e.g. with Spring @Async or with thenCompose())
    – Didier L
    Commented Mar 6, 2018 at 14:57
  • @DidierL I've got a method that executes quick tasks synchronously, but returns a CompletionStage. Why? Because the caller wants to validate input parameters synchronously before chaining asynchronous CompletionStages after it, and it needs any exceptions thrown by precondition validation to get handled by exceptionally().
    – Gili
    Commented Mar 6, 2018 at 19:46

2 Answers 2

32

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);
16

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.