typestar

Functions that raise in Mojo

A def cannot raise unless its signature says so.

def factorial(n: Int) raises -> Int:
    if n < 0:
        raise Error("factorial needs a non-negative input")
    var result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def main() raises:
    print(factorial(6))
    print(factorial(0))

How it works

  1. factorial guards its input and raises an Error on a negative.
  2. raises sits between the argument list and the return arrow.
  3. Callers handle it or are marked raises themselves, as main is.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
225
Tokens
62
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 6 of 6 in Variables & functions, step 6 of 26 in Language basics.

← Previous Next →