Course of Raku / Objects, I/O, and
exceptions / Exceptions / The CATCH phaser / Exercises / Survive a loop
Solution: Survive a loop
Here is a possible solution to the task.
Code
for 1, 2, 3 -> $n {
if $n == 2 {
die "bad: $n";
}
say "ok: $n";
CATCH {
default {
say "caught: " ~ .message;
}
}
}🦋 You can find the source code in the file survive-a-loop.raku.
Output
ok: 1
caught: bad: 2
ok: 3Comments
The
CATCHphaser handles an exception thrown inside the loop body, so thedieon the second iteration is caught rather than fatal.Once the exception is handled, the loop simply continues with the next value, which is why
ok: 3is still printed.