The CATCH phaser
Earlier in this chapter, we used the try
block to catch exceptions. If the exceptions happen inside the try
block, it sets the $!
variable, which you can check later.
In Perl 6, this is not the only method to handle exceptions. Let's return to the previous program but this time we'll use the CATCH
block:
my $a = prompt 'Enter dividend > '; my $b = prompt 'Enter divisor > '; my $c = $a / $b; say "The result of $a / $b is $c."; say 'Done.'; CATCH { say 'Exception caught!'; }
Run the program:
$ perl6 division.pl Enter dividend > 10 Enter divisor > 0 Exception caught! Attempt to divide 10 by zero using div in block <unit> at 07.pl line 4 Actually thrown at: in block <unit> at 07.pl line 4
As soon as the division by zero happens and its result is used, the CATCH
block is triggered. A CATCH
block is one of the phasers in Perl 6, which we discussed in Chapter 2, Writing Code. The compiler passes execution to this block when an exception occurs, and...