What is CompletableFuture.failedFuture() in Java?

Overview

failedFuture() is a static method of the CompletableFuture class. It is used to get a new CompletableFuture completed exceptionally with the given exception. This method was introduced in Java version 9.

The failedFuture method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class use the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


public static <U> CompletableFuture<U> failedFuture(Throwable ex)

Parameters

  • Throwable ex: The exception with which the future gets completed.

Return value

This method returns a new CompletableFuture.

Code

Let’s look at the code below:

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
Throwable exception = new RuntimeException("Runtime exception thrown by future");
CompletableFuture<String> completableFutureCompletedExceptionally = CompletableFuture.failedFuture(exception);
try{
completableFutureCompletedExceptionally.join();
}catch (Exception ex){
System.out.println("Exception Message - " + ex.getMessage());
}
}
}

Explanation

  • Line 1: We import the relevant classes from the concurrent package.
  • Line 6: We define the exception of the completed CompletableFuture and name it exception.
  • Line 8: We get a CompletableFuture completed exceptionally using the failedFuture() method, passing exception as the argument to the method.
  • Lines 10 to 14: We invoke the join() method on the future object. The join() method is wrapped by the try/catch block. The exception message is printed in the catch block.

Free Resources