In the previous example, the try block contained the instructions for both math calculations and printing the result. In real programs, these actions are often separated. Let us re-write the program so that it divides the numbers in a separate subroutine:
my $a = prompt 'Enter dividend > '; my $b = prompt 'Enter divisor > '; my $c = calculate($a, $b); say 'Now ready to print'; say "The result of $a / $b is $c."; say 'Done.'; sub calculate($a, $b) { return $a / $b; }
Now the dangerous action happens inside the calculate function and the result is used outside it.
Run the program with values that should cause exception:
$ perl6 division.pl Enter dividend > 10 Enter divisor > 0 Now ready to print Attempt to divide 10 by zero using div in block <unit> at 06.pl line 7 Actually thrown at: in...