πŸ“˜ Divide by zero in Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s