Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Checking the success of eval

by ncw (Friar)
on Apr 21, 2001 at 01:55 UTC ( #74342=note: print w/ replies, xml ) Need Help??


in reply to Checking the success of eval

My favourite gotcha with eval is if you set a die handler then the die handler is called even inside the eval! In fact I consider this a bug in perl - as does the author of "perldoc die"

Eg

$SIG{__DIE__} = sub { print "Caught by die handler: $_[0]"; exit }; eval { die "Oops\n"; }; print "Eval returned error: $@" if $@;
This prints Caught by die handler: Oops.

The fix goes like this :-

$SIG{__DIE__} = sub { print "Caught by die handler: $_[0]"; exit };

eval
{
    local $SIG{__DIE__};
    die "Oops\n";
};

print "Eval returned error: $@" if $@;
Which returns Eval returned error: Oops as anyone would always want.


Comment on Re: Checking the success of eval
Download Code
(tye)Re: Checking the success of eval
by tye (Cardinal) on Apr 21, 2001 at 02:04 UTC

    I consider eval to be an essential feature of Perl and $SIG{__DIE__} to be a mostly bad idea. So if you want to fix the buggy conflict that they have, I really think you should be fixing the die handler and not the eval:

    $SIG{__DIE__}= sub { return if $^S; print "Caught by die handler: @_"; exit; }

    Better still is to avoid die handlers altogether and either use eval to catch the exception or use a destructor or END block to do the clean up.

            - tye (but my friends call me "Tye")
      Thank you for that $^S nugget tye - I shall faithfully inscribe this into all my $SIG{__DIE__} handlers :-)

      I agree with you that eval is essential, but I disagree with you that $SIG{__DIE__} is a completely bad idea. Just think of if like an eval { } or do_stuff round your entire code and you could come to love it ;-) (If it actually worked that way of course!)

      I like $SIG{__DIE__} for CGI's in the form of CGI::Carp which is really very useful - it would be tiresome to be doing that with eval. I also like $SIG{__DIE__} so I can write scripts which mail me when they've blown up!

      I don't see how you would do it with an END block - perhaps you could enlighten me there? How do you know in an END block whether your program is dieing or just exiting and if you can tell how do you get the value of $@ (presuming that some other destructor/END block used eval)?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://74342]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2014-07-12 03:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (238 votes), past polls