Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

BEGIN, END, eval and die.

by zzspectrez (Hermit)
on Nov 19, 2000 at 02:37 UTC ( #42376=perlquestion: print w/ replies, xml ) Need Help??
zzspectrez has asked for the wisdom of the Perl Monks concerning the following question:

I know you can catch the results of die as follows:

eval { ... some code doing somethin ... die "Couldn't do something!\n"; } if ($@) { print "I caught a call to die: $@"; }

This is very usefull. However, I came across a situation where I would like a script to do some initialization on startup and cleanup on shutdown. This can be accomplished using BEGIN {  } and END{  }. However, how do you handle situations where you still want to do your cleanup on the main script exiting due to a die. The End block will run on die, but how do you know why?? You would think the following would work, but it doesnt.

#!/usr/bin/perl -Tw use strict; die "Let's Try to die."; END { print "End block is being executed.\n"; if ($@){ print "We caught a call to die: $@\n"; } }

So what do the monks think?

Thanks!
zzspectrez

Comment on BEGIN, END, eval and die.
Select or Download Code
Re: BEGIN, END, eval and die.
by autark (Friar) on Nov 19, 2000 at 03:00 UTC
    The $@ variable is only set by the eval code if it somehow fails. In your last example, you don't use eval to "catch" this die, so $@ will not be set.

    However, even if you used eval, this will not work for your END-block. You might want to try to install a $SIG{__DIE__} handler instead. Using that to set a variable or something similar, so that you can access the information within the END-block.

    $SIG{__DIE__} = sub { our @reason = @_ }; eval { die "Let's Try to die." }; END { our @reason; if (@reason) { print "We caught a call to die: @reason\n"; } }

    Autark.

      I did not realize the $@ variable is tied just to the eval code. This makes sense.
      Using a $SIG{__DIE__} handler seems to be exactly what I was looking for. Will this work on the windows platform as well?

      THANKS!!
      zzspectrez

        Yes -- but that's only because it's a Perl-generated signal that never touches the OS. So Windows' lack of signal support doesn't even get brought into play.

        perl -e 'print "Just use $^X$\"$]!$/"'
Re: BEGIN, END, eval and die.
by mitd (Curate) on Nov 19, 2000 at 03:28 UTC
    A more complete solution if you wish to trap errors in OO-ish way is Graham Barr's Error. module.

    Although I am not a big fan of throw, try and catch (personal illogical old fart reasons). I have used it where eval... if $@ just wouldn't do and it was relativley painless.

    mitd-Made in the Dark
    'My favourite colour appears to be grey.'

SIGDIE
by Adam (Vicar) on Nov 19, 2000 at 12:17 UTC
    autark makes the excellent suggestion to use $SIG{__DIE__}. The die signal, AKA sigdie, can be caught and handled by a user defined function. This is done by adding the handler to the %SIG associative array. (read %SIG) I've spent plenty of time playing with this device, and I thought I might take a moment to point out a few of the pitfalls. Many of these are mentioned in the documentation for die, warn, eval, $^S, and for %SIG. (The last two are parts of perlvar.) So then, on to the pitfalls.

    Pitfall 1: While eval traps the fatality of sigdie, it does not block the $SIG{__DIE__} handler from being called.

    Solution 1: If you don't want your handler to be used by any eval block, then check $^S at the begining.
    Solution 2: If you have a particular eval block where you don't want the handler to be invoked, then turn it off using local:
    sub Something { local $@; # Don't step on other code. # try eval{ local $SIG{__DIE__}; # No sigdie handler # do stuff that might die } # catch HandleEvalError( $@ ) if $@; }

    Pitfall 2: The sigdie handler can be set at any time, including during compilation (via a BEGIN block). If you set the handler during a BEGIN block and complitation fails before compiling your subroutine, you not only get a function not found error, but you lose the information about the compilation error.

    Solution 1: Declare your handler subroutine before setting the handler.
      <Note>It occurs to me that you might not have realized that you can do this. Here is an example of to what I am refering. The solution is to move the subroutine up in your code, before the BEGIN block:
    BEGIN{ $SIG{__DIE__} = \&FatalErr } # Real problem if compile fails before getting here. sub FatalErr { # do stuff, maybe print @_ or something. }
    Why does moving the sub up work? Well... BEGIN is actually just another sub routine, except that it gets called as soon as its compiled. INIT, by the way, is also a special sub routine, except that it gets called as the last step of the compilation phase. </Note>
    Solution 2: Don't set your handler in a BEGIN block like that. If you want the handle available after compilation is complete, but before code runs, then use an INIT block.

    Pitfall 3: Not so much a pitfall as it is a reminder: Functions called with an ampersand and no argument list are passed the current values of @_. This means (as Plaid once pointed out to me) that your sigdie handler gets the same argument list that die got. One thing to note is that the file/line number appending has already taken place by the time your handler gets @_.

    Pitfall 4: When your handler is finished, Perl continues dieing. This means that not only does the execution end, but Perl prints the error message to STDERR.

    Solution: You might not have thought of that as a pitfall, but I certainly do. Sometimes you want to include a lot of information about the failure. Maybe write it to a file or something, and then make the error message the user sees be something like, "An error occurred. See log, '$log'\n". The trick here is to keep in mind that Perl is about to exit anyway, so why not accelerate the process? BTW Don't do this in your signal handler unless you are also checking $^S. People get mad when eval blocks don't return.

    Pitfall 5: Your handler only gets called if you use die. This means that if you aren't checking your system calls and using die like C's Assert, then you won't get any added functionality.

    Solution: die. Everywhere.

    I hope this helps you out. Please do read the documentation sited above. Also, don't forget the power of an END block.

    A few of my past posts on the subject:
    Fun with $SIG{__DIE__}         And yet more $SIG{__DIE__} fun...         END failed--call queue aborted

      Thanks, I will have to play with these ideas and see how I can use these to my advantage. I apreciate the refrences, it looks like time to start reading!

      zzspectrez

      Just to clarify things... when anybody executes a die the program is basically done. Even if you wrap an eval around it the script is still going to terminate?

      The reason I am asking is because a module that somebody at work wrote executes a die when there is a request for data that doesn't exist. In the program he has used this for that might be a valid path of execution, but in the program I have written I can't just terminate. I was planning on wrapping an eval around the function call to trap it and more or less ignore it because for me it isn't fatal, but maybe eval won't help?

      Just curious, because I'd rather not have to ask this guy to change his code and just deal with the problem myself. This man scares me to death, hehe ;)

        The basic rule is that if die is called, your program terminates. As with all rules, this one has exceptions. eval is like a separate program. The eval call will terminate, but will not end your program.

        However, it WILL call any handler you have defined in $SIG{__DIE__}. This is something you must keep in mind when writing a sigdie handler. Either check $^S, or don't plan on actually terminating. A large part of my post concerned the pitfalls surounding this point.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-07-13 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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








    Results (248 votes), past polls