typestar

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

  1. The try block holds the calls that might raise.
  2. except e: binds the error so it can be inspected.
  3. String(e) renders the message for printing.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Errors, step 24 of 26 in Language basics.

← Previous Next →