Skip to content

Instantly share code, notes, and snippets.

@joa
Created October 7, 2013 17:37
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 joa/6871816 to your computer and use it in GitHub Desktop.
Save joa/6871816 to your computer and use it in GitHub Desktop.
Unchecked exception handling in Java 8
package brutus.compiler.util;
/**
* import static Unchecked.unchecked
* unchecked(() -> throw new IOException());
*/
public final class Unchecked {
@FunctionalInterface
public static interface UncheckedFunction {
public void apply() throws Throwable;
}
public static void unchecked(final UncheckedFunction f) {
try {
f.apply();
} catch(final Throwable throwable) {
uncheckedThrow(throwable);
}
}
private static void uncheckedThrow(final Throwable t) {
Unchecked.<RuntimeException>throwWithUncheckedCast(t);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwWithUncheckedCast(final Throwable t) throws T {
throw (T)t;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment