Tuesday, October 20, 2009

Exception Handling: Part 04 of 05

Part 4: Tying up loose ends with the $SIG{__DIE__}

Target Audience: This pitch would interest a developer interested in the Exception Handling Best Practices in Perl. This series starts with basic exception handling and adds complexity, ending with pragmatic Best Practices recommendation.

local $SIG{__DIE__} = sub {
my $e = shift;
if ($e->isa('My::Exception::Base')) {
die $e;
} else {
die My::Exception::Base->new($e);
}
};

All this does is cast an exception into an Exception::Class type. If already that, then simply thrown as exception with 'die'.

Clever, huh? This works because $SIG{__DIE__} is called invisibly FIRST, BEFORE ANYTHING ELSE when an exception is thrown, and the program continues to 'die' upon the handler's return. (Hence, DO NOT trap exceptions with $SIG{__DIE__} !)

Why is the $SIG{__DIE__} handler declared local?

No comments:

Post a Comment