What happens when a CompletableFuture throws an exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
public class AsynchronousExceptions { | |
public static void main(final String[] args) throws InterruptedException { | |
for (final boolean failure : new boolean[]{false, true}) { | |
CompletableFuture<Integer> x = CompletableFuture.supplyAsync(() -> { | |
if (failure) { | |
throw new RuntimeException("Oops, something went wrong"); | |
} | |
return 42; | |
}); | |
try { | |
// Blocks (avoid this in production code!), and either returns the promise's value, or... | |
System.out.println(x.get()); | |
System.out.println("isCompletedExceptionally = " + x.isCompletedExceptionally()); | |
// Output[failure=false]: 42 | |
// Output[failure=false]: isCompletedExceptionally = false | |
} catch (ExecutionException e) { | |
// ... rethrows the RuntimeException wrapped as an ExecutionException | |
System.out.println(e.getMessage()); | |
System.out.println(e.getCause().getMessage()); | |
System.out.println("isCompletedExceptionally = " + x.isCompletedExceptionally()); | |
// Output[failure=true]: java.lang.RuntimeException: Oops, something went wrong | |
// Output[failure=true]: Oops, something went wrong | |
// Output[failure=true]: isCompletedExceptionally = true | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment