completeExceptionally()
is an instance method of the CompletableFuture
which is used to complete the get()
and join()
throwing the given exception.
The completeExceptionally
method is defined in the CompletableFuture
class. The CompletableFuture
class is defined in the java.util.concurrent
package. To import the CompletableFuture
class, we check the following import statement.
import java.util.concurrent.CompletableFuture;
public boolean completeExceptionally(Throwable ex)
Throwable ex
: The exception to throw.This method returns true
if the method call resulted in the transition of the CompletableFuture
to a completed state. Otherwise, it returns false
.
Let’s take a look at the code.
import java.util.concurrent.*;public class Main {public static void main(String[] args) {CompletableFuture<Integer> completableFuture = new CompletableFuture<>();RuntimeException runtimeException = new RuntimeException("Runtime Exception");boolean flag = completableFuture.completeExceptionally(runtimeException);if(flag) System.out.println("Future moved to completed stage");if(completableFuture.isCompletedExceptionally()) System.out.println("Future completed exceptionally");Integer result = null;try {result = completableFuture.get();} catch (InterruptedException | ExecutionException e) {System.out.println("Exception while getting the result of the future. " + e.getMessage());}System.out.println("Result - " + result);}}
concurrent
package.CompletableFuture
that is incomplete using the constructor of the CompletableFuture
class.completeExceptionally()
method, the future created in line 5 is moved to the completed stage with the exception defined in line 6. The completeExceptionally()
method returns a Boolean
that’s stored in the flag
variable.flag
value, we print whether the future was moved to the completed stage or not.isCompletedExceptionally()
, we check whether the future was completed exceptionally or not.get()
method. At this point, the exception defined in line 6 is thrown and caught in the catch block.null
as initialized and null
will be printed to the console.