Recovering from an error in Mojo
A raising helper wrapped by a caller that supplies a fallback.
def ratio(top: Int, bottom: Int) raises -> Float64:
if bottom == 0:
raise Error("cannot divide by zero")
return Float64(top) / Float64(bottom)
def safe_ratio(top: Int, bottom: Int) -> Float64:
try:
return ratio(top, bottom)
except e:
print("falling back:", String(e))
return 0.0
def main():
print(safe_ratio(7, 2))
print(safe_ratio(7, 0))
How it works
ratiorefuses a zero denominator and raises instead.safe_ratiocalls it insidetryand returns the result on success.- The
exceptarm reports the problem and returns0.0in its place.
Keywords and builtins used here
ErrorFloat64IntStringdefexceptifmainprintraiseratioreturnsafe_ratiotry
The run, in numbers
- Lines
- 15
- Characters to type
- 340
- Tokens
- 96
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 72 seconds.
Step 3 of 3 in Errors, step 25 of 26 in Language basics.