Created
October 7, 2013 17:37
-
-
Save joa/6871816 to your computer and use it in GitHub Desktop.
Unchecked exception handling in Java 8
This file contains hidden or 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
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