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
factorialguards its input and raises anErroron a negative.raisessits between the argument list and the return arrow.- Callers handle it or are marked
raisesthemselves, asmainis.
Keywords and builtins used here
ErrorIntdeffactorialforifmainprintraiserangereturnvar
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.
Step 6 of 6 in Variables & functions, step 6 of 26 in Language basics.