Last active
August 22, 2023 07:00
-
-
Save htsign/22565c5d7e587935b0b5f200ccb62a89 to your computer and use it in GitHub Desktop.
Lambda expression implementation with wrapping Checked exception for Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WrapperException extends RuntimeException { | |
WrapperException(Exception e) { | |
super(e); | |
} | |
} |
Author
htsign
commented
Jan 30, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment