Look Mom, No Checked Exception
I'm probably showing off an old trick here, but a fierce discussion over at the Norwegian JUG forum reminded me of it, and I thought I'd share it with new dogs who want to learn old tricks.
The cause of the controversy is the ever so popular topic; which is better checked or unchecked exceptions?
Since the release of Java 1.4, a secret class named sun.misc.Unsafe has been hiding within the JDK. You can use this class to pull some amazing tricks, including throwing checked exceptions without having to include these exceptions in the method signature. How? Take a look at this little snippet:
public void LookMomNoCheckedException() // <- No throws clause!
{
Field field;
Unsafe unsafe;
try
{
field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
}
catch (Exception e)
{
throw new RuntimeException("Sorry, only checked exceptions for you my friend.", e);
}
// Let's throw a checked exception...
unsafe.throwException(new Exception("Look mom no checked exception!"));
}
Voila! You've just thrown a checked exception from within a method without a throws clause - although I think this kind of code will cause even more controversy than the (not so) good old checked exceptions.
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using