Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Created September 22, 2022 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viveknaskar/fc0b11e8c6c792ae47f70ab054454975 to your computer and use it in GitHub Desktop.
Save viveknaskar/fc0b11e8c6c792ae47f70ab054454975 to your computer and use it in GitHub Desktop.
Illustration of exceptionally method of CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ExceptionallyExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
int val = 0;
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
if(val == 0) {
throw new IllegalArgumentException("Value is 0");
}
if(val > 0) {
return "Positive value!";
} else {
return "Negative value!";
}
}).exceptionally(ex -> { // printing error messages & returning a default value
System.out.println("Failed due: " + ex.getMessage());
return "Default value!";
});
//get() blocks and gets the result of the Future
System.out.println(completableFuture.get());
}
}
/***************************************************************************
* Output:
* Failed due: java.lang.IllegalArgumentException: Value is 0
* Default value!
**************************************************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment