try and except in Mojo
Catching an error keeps the program running.
def parse_count(text: String) raises -> Int:
if text == "":
raise Error("empty input")
return Int(text)
def main():
try:
print(parse_count("17"))
print(parse_count(""))
except e:
print("recovered:", String(e))
How it works
- The
tryblock holds the calls that might raise. except e:binds the error so it can be inspected.String(e)renders the message for printing.
Keywords and builtins used here
ErrorIntStringdefexceptifmainparse_countprintraisereturntry
The run, in numbers
- Lines
- 11
- Characters to type
- 210
- Tokens
- 63
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 44 seconds.
Step 2 of 3 in Errors, step 24 of 26 in Language basics.