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
- Each guard checks one precondition and raises with a message.
String(balance)folds a value into the error text.- The return is reached only when both guards let the call through.
Keywords and builtins used here
ErrorIntStringdefifmainprintraisereturnwithdraw
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.
Step 1 of 3 in Errors, step 23 of 26 in Language basics.