Skip to content

Instantly share code, notes, and snippets.

@marccarre
Created May 8, 2016 16:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marccarre/2439456da4b63dfb0c2e931ce1204b01 to your computer and use it in GitHub Desktop.
Save marccarre/2439456da4b63dfb0c2e931ce1204b01 to your computer and use it in GitHub Desktop.
What happens when a CompletableFuture throws an exception
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