Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException
uncatchable?
Thoughts that came to m
A variant on the theme is the surprising fact that you can throw undeclared checked exceptions from Java code. Since it is not declared in the methods signature, the compiler won't let you catch the exception itself, though you can catch it as java.lang.Exception.
Here's a helper class that lets you throw anything, declared or not:
public class SneakyThrow {
public static RuntimeException sneak(Throwable t) {
throw SneakyThrow. throwGivenThrowable(t);
}
private static RuntimeException throwGivenThrowable(Throwable t) throws T {
throw (T) t;
}
}
Now throw SneakyThrow.sneak(new ChuckNorrisException());
does throw a ChuckNorrisException, but the compiler complains in
try {
throw SneakyThrow.sneak(new ChuckNorrisException());
} catch (ChuckNorrisException e) {
}
about catching an exception that is not thrown if ChuckNorrisException is a checked exception.