Hi Richard,

This has something to do with lazy evaluation. It triggers the calculation when it wants to show the value in $r. So commenting out the first 'say' will error on the second with the shown response. The CATCH is not at the same scope than the second 'say' statement so there you get a different action.

Something interesting might be when changing the expression into '$r = 5 / (3 - $s).Num;' You get a different response and you will not need the CATCH at all. Just test on Inf if you need to change it.

An example;

use v6;

my $r;
for 0..4 -> $s {
   $r = (5 / (3 - $s));
   $r = 42 if $r.Num ~~ Inf;

   say "At line $?LINE r is $r";
}

Response

At line 10 r is 1.666667
At line 10 r is 2.5
At line 10 r is 5
At line 10 r is 42
At line 10 r is -5

Greetings,
Marcel

Marcel and Moritz,

Thank you for the fast response.

I have been experimenting with the code you sent, but still do not
understand something. To illustrate, here is another snippet:
use v6;
my $r;
for 0..4 -> $s {
   {
     $r = 5 / (3 - $s);
     say "At line $?LINE r is $r";
     CATCH {
       when X::Numeric::DivideByZero { $r = 65 }
       default { $r = 55 }
     }
    }
    say "At line $?LINE r is $r";
}
### result is
At line 6 r is 1.666667
At line 12 r is 1.666667
At line 6 r is 2.5
At line 12 r is 2.5
At line 6 r is 5
At line 12 r is 5
At line 12 r is 65
At line 6 r is -5
At line 12 r is -5

#### However,
use v6;
my $r;
for 0..4 -> $s {
   {
     $r = 5 / (3 - $s);
     say "At line $?LINE r is $r";
     CATCH {
       when X::Numeric::DivideByZero { $r = 65 }
       default { $r = 55 }
     }
    }
    say "At line $?LINE r is $r";
}
#### result is
At line 12 r is 1.666667
At line 12 r is 2.5
At line 12 r is 5
Attempt to divide 5 by zero using div
  in block <unit> at test.pl line 12

Actually thrown at:
  in block <unit> at test.pl line 12

It seems that the commented out 'say' statement is required to get the
CATCH statement to "trigger".
a) Why is the exception not caught the assignment statement?
b) What other statement (NO OP) can I use in place of the commented
out 'say' statement?

Clearly, I do not have a good understanding of the Exception
mechanism. Your help in understanding is appreciated.

Richard


Reply via email to