10

I'd like to create a CompletableFuture that has already completed exceptionally.

Scala provides what I'm looking for via a factory method:

Future.failed(new RuntimeException("No Future!"))

Is there something similar in Java 10 or later?

Holger
  • 285,553
  • 42
  • 434
  • 765
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171

2 Answers2

29

I couldn't find a factory method for a failed future in the standard library for Java 8 (Java 9 fixed this as helpfully pointed out by Sotirios Delimanolis), but it's easy to create one:

/**
 * Creates a {@link CompletableFuture} that has already completed
 * exceptionally with the given {@code error}.
 *
 * @param error the returned {@link CompletableFuture} should immediately
 *              complete with this {@link Throwable}
 * @param <R>   the type of value inside the {@link CompletableFuture}
 * @return a {@link CompletableFuture} that has already completed with the
 * given {@code error}
 */
public static <R> CompletableFuture<R> failed(Throwable error) {
    CompletableFuture<R> future = new CompletableFuture<>();
    future.completeExceptionally(error);
    return future;
}
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
18

Java 9 provides CompletableFuture#failedFuture(Throwable) which

Returns a new CompletableFuture that is already completed exceptionally with the given exception.

that is more or less what you submitted

/**
 * Returns a new CompletableFuture that is already completed
 * exceptionally with the given exception.
 *
 * @param ex the exception
 * @param <U> the type of the value
 * @return the exceptionally completed CompletableFuture
 * @since 9
 */
public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
    if (ex == null) throw new NullPointerException();
    return new CompletableFuture<U>(new AltResult(ex));
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724