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;
public static <U> CompletableFuture<U> failedFuture(Throwable ex)
Throwable ex
: The exception with which the future gets completed.This method returns a new CompletableFuture
.
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());}}}
concurrent
package.CompletableFuture
and name it exception
.CompletableFuture
completed exceptionally using the failedFuture()
method, passing exception
as the argument to the method.join()
method is wrapped by the try/catch
block. The exception message is printed in the catch
block.