Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Catching a 'division by zero' error with Exception::Class

by moritz (Cardinal)
on Sep 15, 2008 at 14:40 UTC ( [id://711474]=note: print w/replies, xml ) Need Help??


in reply to Catching a 'division by zero' error with Exception::Class

Your program dies before it gets to the line with MyException->throw, because the division by zero happens before.

One way to catch that kind of error is by assigning a handler to $SIG{__DIE__}. But maybe Exception::Class even has a mechanism for automatically wrapping such errors.

Replies are listed 'Best First'.
Re^2: Catching a 'division by zero' error with Exception::Class
by massa (Hermit) on Sep 15, 2008 at 15:48 UTC
    The compiler is catching the division by zero before your code has any opportunity to tackle it. I made the following work:
    #!/usr/bin/env perl use Exception::Class ( 'MyException' ); # try my $z = 0; eval { eval { my $result = ( 23 / $z ) } || MyException->throw( error => 'I feel funny.' ) }; # my $e; # catch if( my $e = Exception::Class->caught( 'MyException' ) ) { warn $e->error, "\n", $e->trace->as_string, "\n"; warn join ' ', $e->euid, $e->egid, $e->uid, $e->gid, $e->pid, $e->ti +me; exit; } else { $e = Exception::Class->caught(); ref $e ? $e->rethrow : die $e; } __END__ I feel funny. Trace begun at index.pl line 9 eval {...} at index.pl line 8 1000 1000 1000 121 120 117 115 109 108 106 104 46 44 30 29 25 24 20 6 +4 0 1000 1000 1000 121 120 117 115 109 108 106 104 46 44 30 29 25 24 +20 6 4 0 10107 1221493762 at index.pl line 17.
    []s, HTH, Massa (κς,πμ,πλ)
      dear massa, thanks for your help. Would you mind to give a quick explanation of the effect of this eval wrapper around the division by zero expression?

        The important bit is that you are eval-ing the '27/0', but the "|| throw exception" part is outside the eval. So when the eval dies out of the execution and returns false, the exception is thrown.

        The structure is eval {"risky expression"} or throw exception.
        NOT eval {"risky expression; or throw exception"}

        It should be noted that the return value of eval is:

        "...the value of the last expression evaluated inside the mini-program; a return statement may be also used, just as with subroutines."
        So, you should add a "1;" or "return 1;" to the end, otherwise you would throw some spurious exceptions if the answer is supposed to be zero (such as 5*2-10)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-03-28 20:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found