Skip to content

Instantly share code, notes, and snippets.

@htsign
Last active August 22, 2023 07:00
Show Gist options
  • Save htsign/22565c5d7e587935b0b5f200ccb62a89 to your computer and use it in GitHub Desktop.
Save htsign/22565c5d7e587935b0b5f200ccb62a89 to your computer and use it in GitHub Desktop.
Lambda expression implementation with wrapping Checked exception for Java
public class ExceptionWrapper {
@SuppressWarnings("unchecked")
public static <T, E extends Exception> T exec(ThrowableSupplier<T, E> func, Function<E, T> orElse) {
try {
return func.getThrowable();
}
catch (WrapperException e) {
Throwable cause = e.getCause();
if (cause instanceof Exception) {
return orElse.apply((E) cause);
}
throw e;
}
}
}
@FunctionalInterface
interface ThrowableSupplier<T, E extends Exception> {
T get() throws E;
@SuppressWarnings("unchecked")
default T getThrowable() {
try {
return get();
}
catch (Exception e) {
throw new WrapperException((E) e);
}
}
}
public class WrapperException extends RuntimeException {
WrapperException(Exception e) {
super(e);
}
}
@htsign
Copy link
Author

htsign commented Jan 30, 2021

ExceptionWrapper.exec(() -> someThrowableMethod(arg0, arg1, arg2), e -> resolve(e));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment