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.

Didier L
  • 18,905
  • 10
  • 61
  • 103
Gili
  • 86,244
  • 97
  • 390
  • 689
  • 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 Mar 06 '18 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 `CompletionStage`s after it, and it needs any exceptions thrown by precondition validation to get handled by `exceptionally()`. – Gili Mar 06 '18 at 19:46

2 Answers2

31

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);
M. Justin
  • 14,487
  • 7
  • 91
  • 130
Gili
  • 86,244
  • 97
  • 390
  • 689
15

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

Didier L
  • 18,905
  • 10
  • 61
  • 103