📘 Divide by zero in Perl 6

📘 Divide by zero in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Do something with the division by zero.

Division by zero in itself is not an immediate error in Perl 6.

The following code does not generate an exception and prints the message after the problematic division.

my $v = 42 / 0;
say 'It still works!';

However, as soon as the result stored in the $v variable is about to be displayed, the program stops execution with an error:

my $v = 42 / 0;
say $v;

The error message appears in the console:

Attempt to divide 42 by zero using div
  in block <unit> at divide0.pl line 2

The above-mentioned behaviour is called soft failure. It fails only if someone sees it 🙂 To catch the error, use the tryand the CATCH blocks:

try {
    say 42 / 0;
    CATCH {
        default {
            say 'Error!';
        }
    }
}
say 'It still works!';

Leave a Reply