typestar

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

  1. ratio refuses a zero denominator and raises instead.
  2. safe_ratio calls it inside try and returns the result on success.
  3. The except arm reports the problem and returns 0.0 in its place.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Errors, step 25 of 26 in Language basics.

← Previous Next →