[Wellington-pm] Rethrowing exceptions

Ewen McNeill ewen at naos.co.nz
Mon Nov 6 16:44:03 PST 2006


In message <E1Ggvwp-0003VJ-00 at israel.diaspora.gen.nz>, michael at diaspora.gen.nz w
rites:
>>What I'm looking for is something equivilent to rethrowing the same
>>exception object in Java, or an empty throw in C++.   [....]
>
>I can't speak to fancy stack traces, and things, but this works for me:[...]
>	if ($@) { print $@; die $@; 

That does work for preserving the message and file/line number
(providing you don't manage to lose the contents of $@ in your cleanup
code -- which turned out to be my initial problem; "local $@" to the
rescue there).

Unfortunately it seems to confuse Devel::StackTrace (as used by
Catalyst::Plugin::StackTrace), which means that the stack trace is around
the second die, not the first one.  (From the bit of Devel::StackTrace
I read, this is due to it tracing the stack in a local DIE handler,
using caller(), presumably because Perl "exceptions" don't include
reliable stack information by default.)

Carp or throwing special exceptions doesn't seem to solve my problem
since I'm wanting to preserve an exception that I'm not generating, and
interact with stack traceback code which I didn't write (and of which I 
don't want to maintain a custom version).

The precise context is that I'm writing a Catalyst plugin which
intercepts database action and does some actions of its own, and if 
the original database action fails then I want to cleanup my own actions
before allowing the control flow to return.

In message <1162798112.8371.22.camel at localhost.localdomain>, Grant McLean writes:
>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.

As it happens I don't care what went wrong, only the binary situation
"all went well"/"something went wrong".  I just want to be able to 
catch the exception, do some cleanup, and then propogate the exception
for further handling.  Languages with "real" exceptions (Java, C++, etc)
support this.  Perl (5)'s exceptions seem to be a little too much of an
afterthought to support this generically.

So the answer appears to be that there's no generic way to rethrow an
exception that was caught "as if" it were the continuing propogation 
of the original exception.  But that if you control all the code you can 
do something which will simulate this.

Thanks for the suggestions.  I think I'll just live with the broken
stack traceback.

Ewen


More information about the Wellington-pm mailing list