[Wellington-pm] Rethrowing exceptions

Grant McLean grant at mclean.net.nz
Sun Nov 5 23:28:32 PST 2006


On Mon, 2006-11-06 at 17:04 +1300, Ewen McNeill wrote:
> Hi,
> 
> In perl you can (sort of) do exception handling by doing:
> 
> eval { 
>    # some stuff
>    die "It broke";
> };
> 
> if ($@) {
>   print "Oh dear, it didn't work, because: $@\n";
> }
> 
> However I can't find any obvious way of rethrowing an exception

As Michael said, you re-throw an exception by saying:

  die $@;


If you initially throw the exception by calling die like this ...

  die "too many squingles";

... then if your string doesn't end with a newline, perl will append 
" at <filename> line <number>.\n" to the string before storing it in $@.
Consequently, if you re-throw the exception it will retain the filename
and line number of where the exception originally occurred.

If you want a stack trace rather than just a line number then Carp.pm (a
core module) is the standard tool.  You can either use 'confess' instead
of die whenever you want a stack trace or you can enable 'verbose' mode
and always use croak:

  use Carp qw(verbose croak);


If you're testing whether an exception was something you can handle,
then you probably want to use exception objects rather than passing a
string to die and then later testing it with a regex.  I can't say I've
done that much myself, but Exception::Class seems to be an effective
tool.

The Error.pm module is an alternative tool for exception objects which
offers some syntactic sugar in the form of try/catch blocks.
Unfortunately, nesting them leads to memory leaks which kind of limits
their usefulness.

Cheers
Grant



More information about the Wellington-pm mailing list