Course of Raku / Objects, I/O, and exceptions / Exceptions / Exception objects / Exercises / Match the type
Solution: Match the type
Here is a possible solution to the task.
Code
{
my $x = 1 / 0;
say $x;
CATCH {
when X::Numeric::DivideByZero {
say 'cannot divide by zero';
}
}
}🦋 You can find the source code in the file match-the-type.raku.
Output
cannot divide by zeroComments
In Raku,
1 / 0does not blow up immediately; it produces a lazyFailure. The exception is thrown only when we use the value, here by trying tosayit.The thrown exception is of the built-in type
X::Numeric::DivideByZero, andwhen X::Numeric::DivideByZeromatches it precisely. Matching on a specific type, rather than catching everything withdefault, lets you handle different errors in different ways.