Skip to content

Instantly share code, notes, and snippets.

@thirdy
Created August 19, 2016 07:06
Show Gist options
  • Save thirdy/fe130f6da4158c33cc1d9bbaa638db12 to your computer and use it in GitHub Desktop.
Save thirdy/fe130f6da4158c33cc1d9bbaa638db12 to your computer and use it in GitHub Desktop.
/**
* Wrap a Supplier in a try-catch, if an exception of class exceptionClass is caught, an empty Optional is returned.
*/
public static <T> Optional<T> expect(Supplier<T> supplier, Class<? extends Exception> exceptionClass) {
try {
return Optional.ofNullable(supplier.get());
}
catch (Exception ex) {
if (exceptionClass.isInstance(ex)) {
return Optional.empty();
}
throw ex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment