Course of Raku / Objects, I/O, and exceptions / Exceptions / Soft failures / Exercises / Soft reciprocal
Solution: Soft reciprocal
Here is a possible solution to the task.
Code
sub reciprocal($n) {
fail 'no reciprocal of zero' if $n == 0;
return 1 / $n;
}
say reciprocal(4);
say reciprocal(0) // 'undefined';🦋 You can find the source code in the file soft-divide.raku.
Output
0.25
undefinedComments
reciprocal(4)returns1 / 4, that is0.25, normally.reciprocal(0)callsfail, so it returns aFailure, which is undefined. The//operator returns its right-hand side whenever the left side is undefined, so we get the fallbackundefined.Using
//counts as handling the failure: it tests for definedness without using the value, so theFailurestays soft and is never thrown as a real exception.