typestar

Raising errors in Mojo

raise Error(...) rejects input a function cannot honor.

def withdraw(balance: Int, amount: Int) raises -> Int:
    if amount <= 0:
        raise Error("amount must be positive")
    if amount > balance:
        raise Error("insufficient funds: " + String(balance))
    return balance - amount

def main() raises:
    print(withdraw(100, 30))
    print(withdraw(70, 70))

How it works

  1. Each guard checks one precondition and raises with a message.
  2. String(balance) folds a value into the error text.
  3. The return is reached only when both guards let the call through.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
277
Tokens
70
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 1 of 3 in Errors, step 23 of 26 in Language basics.

← Previous Next →