Skip to content

Instantly share code, notes, and snippets.

@valtoni
Created December 3, 2019 11:14
Show Gist options
  • Save valtoni/f455ddaab435c0f671fa9f66f0005f17 to your computer and use it in GitHub Desktop.
Save valtoni/f455ddaab435c0f671fa9f66f0005f17 to your computer and use it in GitHub Desktop.
Consumer handling exception (credit: https://www.baeldung.com/java-lambda-exceptions)
static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(
ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
try {
E exCast = exceptionClass.cast(ex);
System.err.println(
"Exception occured : " + exCast.getMessage());
} catch (ClassCastException ccEx) {
throw new RuntimeException(ex);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment