3 ms·
> unlike languages that use exceptions for errors I present to you Sneaky Throw, credit to the author in [1] public class Sneak { public static RuntimeE
by koito17 3y ago
> unlike languages that use exceptions for errors
I present to you Sneaky Throw, credit to the author in [1]
public class Sneak {
public static RuntimeException sneakyThrow(Throwable t) {
if ( t == null )
throw new NullPointerException("t");
Sneak.<RuntimeException>sneakyThrow0(t);
return null;
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow0(Throwable t) throws T {
throw (T)t;
}
}
Now you too can force your callers to accidentally swallow errors and have the code compile ;)
[1] https://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html https://www.mail-archive.com/javaposse@googlegroups.com/msg0...
- josephcsible 3y agoThat lets you subvert checked exceptions, but the sneakily thrown exception will still be thrown and bubble up, not silently ignored.