More Checked Exception Madness

Published 17 July 07 05:01 PM | andersnoras 

My post on throwing undeclared checked exceptions got some attention. Of course you shouldn't use the sun.misc.Unsafe class, but what about these nuggets contributed by my readers?

public void lookMomHeresANastyOldie()
{
    Thread.currentThread().stop(
        new Exception("Look mom no checked exception here either!")
    );    
}

The thread's stop method was deprecated way back in 1998, but its still callable for backward compability reasons.
If you're not into using deprecated methods, what about this nugget that ".k" made me aware of?

// We're gonna need some help here, 
// so let's bring in the baseball team
public class Pitcher
{
    private static Throwable throwable;
    private Pitcher() throws Throwable
    {
        throw throwable;
    }
    public static synchronized void throwIt(Throwable throwable) {
        Pitcher.throwable = throwable;
        try
        {
            Pitcher.class.newInstance();
        }
        catch (InstantiationException e)
        {
            // pass
        }
        catch (IllegalAccessException e)
        {
            // pass
        }
        finally
        {
            Pitcher.throwable=null;
        }
    }
}

To throw an undeclared checked exception just delegate the throwing to the pitcher...

public void lookMomHeresAnotherOne()
{
    Pitcher.throwIt(
new Exception("Guess you didn't see this one coming.")
); }

Johannes posted a follow up to my original post on catching these undeclared checked exceptions. Basically, you cannot catch these exceptions as typed exceptions because the compiler can't see how these exception can occur.

So to the grand question, how can an undeclared checked excpetion be thrown? The rules for checked exceptions are enforced at compile time, but not at runtime. The java.misc.Unsafe method does some pretty nasty things beneath the covers, first it gets hold of the stack and excution poiters and then it inspects the stack to figure out where to carry on its processing. If a catch block exists, it will continue there, if it's a synchronized method it will exit the current monitor before continuing execution and so forth. The bottom line is that the propagation of the exception is not handled by the JVM, but rather by a class that is reimplementing the JVM's behavior. This goes to show that something that looks as nasty as throwing unchecked, checked exception is probably even more nasty than it appears.

Filed under:

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 RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Enter the code you see below