isCompletedExceptionally()
is an instance method of the CompletableFuture
. It checks whether the future is completed with any exceptions. The possible reasons for a future to complete exceptionally are:
The isCompletedExceptionally
method is defined in the CompletableFuture
class. The CompletableFuture
class is defined in the java.util.concurrent
package. To import the CompletableFuture
class, check the following import statement:
import java.util.concurrent.CompletableFuture;
public boolean isCompletedExceptionally()
The method has no parameters.
This method returns true
if the future is completed exceptionally. Otherwise, it returns false
.
import java.util.concurrent.*;public class Main {public static void main(String[] args) throws ExecutionException, InterruptedException {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 = completableFuture.get();System.out.println("Result - " + result);}}
CompletableFuture
class.completeExceptionally()
method, the future we create in line 5 is moved to the completed stage. This is done with the exception defined in line 6. The completeExceptionally()
method returns a Boolean stored in the flag
variable.flag
value, we print whether the future was moved to the completed stage or not.isCompletedExceptionally()
.get()
method. At this point, the exception defined in line 6 is thrown.