New Exceptions stuff

Matts on 2002-08-01T12:41:04

In my previous journal entry I got talking about exception handling, following on doing a talk on it. The problem was I had a $SIG{__DIE__} handler that said "If the exception isn't of type 'MyException' then create a MyException class from the exception". Unfortunately when you try and plug two systems together and one $SIG{__DIE__} overrides another, you get a conflict - case in point TT2 and AxKit - both have exception objects, but both use different base classes, so the exception objects support different methods and are of different types.

After much umming and ahhing, I figured the best thing to do is leave exceptions well alone if they are references (you could say blessed() here, but ref() is normally good enough). If they aren't, you need to figure out what your $SIG{__DIE__} is there for - in my case it's to augment the exception with a stack trace for debugging. Then you simply augment it but just as a string - otherwise you break stuff...

So, in going through this, I think the best use of $SIG{__DIE__} looks like this:

$SIG{__DIE__} = sub {
    my $err = shift;
    return if ref($err);
    die Carp::Heavy::longmess($err) if $DEBUGGING;
    die $err;
};


Which allows you to do:

if ($@) {
    if ($@->isa('My::Exception')) {
        warn("got a My::Exception\n");
    }
    else {
        warn("Don't know this exception type: $@\n");
    }
}


The reason this is better is it allows all systems to work together, and does so without cross-interfering, or requiring all systems to have a common base exceptions class (even though that would be nice). If you did anything else you'd *have* to have a common base exceptions class even if it was just to overload stringification (spent quite a while thinking about this).

I should put this into something more concrete, probably.