Trapping Perl divide-by-zero exceptions using eval( )

G

Griff

Why is it that this code produces a trappable exception -
#--------------------------------

$b = 1;
$c = 0;

eval { $b / $c ; } ;

if ($@)
{
print "I caught an exception\n";
print $@;
}

#--------------------------------

but this code seems to crash without catching the exception -

eval { 1 / 0 ; } ;

if ($@)
{
print "I caught an exception\n";
print $@;
}

I know that the second piece of code is even dumber than the first,
but just wondered what the difference was between the errors produced.

Thanks - Griff
 
S

Scott W Gifford

(e-mail address removed) (Griff) writes:

[...]
but this code seems to crash without catching the exception -

eval { 1 / 0 ; } ;

if ($@)
{
print "I caught an exception\n";
print $@;
}

I know that the second piece of code is even dumber than the first,
but just wondered what the difference was between the errors
produced.

My guess is that this error is produced at compile-time, when the Perl
compiler is calculating constant expressions and your code isn't yet
running. If you eval 1/0 in a string you get a runtime exception, and
if there are any variables at all in the expression (even $a/0) you
get a runtime exception, which seems to support this theory.

For a more definitive answer somebody will probably have to delve into
Perl's guts.

----ScottG.
 
U

Uri Guttman

G> Why is it that this code produces a trappable exception -
G> #--------------------------------

G> $b = 1;
G> $c = 0;

G> eval { $b / $c ; } ;

G> but this code seems to crash without catching the exception -

G> eval { 1 / 0 ; } ;

G> I know that the second piece of code is even dumber than the first,
G> but just wondered what the difference was between the errors produced.

the latter is executed at compile time as perl does constant folding. so
the eval hasn't been compiled yet and can't be run.

uri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top