Hint on local DIE handlers in Eval

David Dick david_dick at iprimus.com.au
Thu Jan 9 23:44:43 CST 2003


sorted.
thanks scott.

Scott Penrose wrote:

>
> On Friday, Jan 10, 2003, at 15:17 Australia/Melbourne, David Dick wrote:
>
>> i've never actually used a DIE handler before.  Why would you use 
>> them?  I understand that intercepting a exception thrown by a die and 
>> informing the user about it in a graceful fashion is a useful 
>> thing(tm), but i tend to use an eval block (or similar such as 
>> Error.pm) around the suspect code and a test afterwards.  Is the DIE 
>> handler just another example of TIMTOWTDI, or does it have specific 
>> advantages/disadvantages (not merely gotchas) associated with it?
>> -dave
>
>
> Well, I guess I could write my code like this...
>
>     eval {
>         Here is ALL my code !!!
>     };
>     if ($@) {
>         Nice error messages here for users to see
>     }
>
> and that would probably work too
>
> The reasons for doing it can be a little more subtle.
>
> Most notably we tend to write code that looks a little like this...
>
>     use MyErrorCode;
>
>     ...
>
> In the MyErrorCode we can then put a die handler, it would not be 
> possible (without code rewrite) to then wrap an eval around the code 
> it is used in. I believe in fact that this is how Error works :-) Yep 
> just checked it. What I was demonstrating is what Error does. But it 
> is still an important lesson even when using Error as you can easily 
> break Error with the wrong DIE handler etc :-)
>
> Another reason is simplicity (not only for the use I did above) but 
> also cause I can do things like this at the start of someone else' cgi 
> script
>
>     $SIG{__DIE__} = sub {
>         print MYLOG "$0 error - $_[0]";
>         die $_[0];
>     };
>
> This is of course a silly example as I have just logged twice :-) but 
> has some point, eg: you may have wanted to use SysLog.
>
> Another reason to learn this stuff is how others work. eg: If you 'use 
> CGI' CGI can create a DIE handler for you.
>
> Scott





More information about the Melbourne-pm mailing list