[Wellington-pm] Rethrowing exceptions

Srdjan srdjan at catalyst.net.nz
Mon Nov 6 12:31:25 PST 2006


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I will only second this by a more elaborate example:

eval {
    # some stuff
    die MyExceptionObjectThatCapturesStackAndGodKnowsWhatElse->new("It broke");
};

if ($@) {
    my $reason = ref($@) ? $@->message() : $@;
    print "Oh dear, it didn't work, because: $reason\n";
    die $@;
}

This way original stack trace is preserved. I don't know of any more elegant way.

Srdjan

Grant McLean wrote:
> 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
> 
> _______________________________________________
> Wellington-pm mailing list
> Wellington-pm at pm.org
> http://mail.pm.org/mailman/listinfo/wellington-pm
> 
> 
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFT5ucZtcHxCitRpgRAqEcAKCPK2NkoqHX4ZCnqrlLaVZRx3DqGgCggOCD
K4f81xvEHYsS9/bmhlOnUbs=
=itC+
-----END PGP SIGNATURE-----


More information about the Wellington-pm mailing list