Course of Raku / Objects, I/O, and exceptions / Exceptions / Soft failures / Exercises / Lookup or not found
Solution: Lookup or not found
Here is a possible solution to the task.
Code
sub lookup($key) {
fail 'no such key' if $key ne 'a';
return 100;
}
my $r = lookup('z');
if $r.defined {
say $r;
}
else {
say 'not found';
say "reason: {$r.exception.message}";
}🦋 You can find the source code in the file lookup.raku.
Output
not found
reason: no such keyComments
lookup('z')callsfail, so it returns an undefinedFailure.Because the result is undefined, the program prints
not foundrather than trying to use the failed value.A
Failurestill carries the exception that describes what went wrong.$r.exceptionretrieves it — which also marks the failure as handled, so it will not blow up later — and.messagereads the text passed tofail,no such key.