Skip to content

Mojo Error: cannot call function that may raise in a context that cannot raise

error: cannot call function that may raise in a context that cannot raise means you called something that can fail with an error, like Int("42") or my_dict[key], from a function that isn’t allowed to fail. In Mojo, a function that can raise has to say so with raises, and every caller has to either handle the error or say raises too. The compiler even tells you both fixes in its notes. For the other errors in this series, see Mojo Errors Explained.

def main():
var n = Int("42")
print(n)
parse.mojo:2:16: error: cannot call function that may raise in a context that cannot raise
var n = Int("42")
~~~^~~~~~
parse.mojo:2:16: note: try surrounding the call in a 'try' block
var n = Int("42")
^
parse.mojo:1:5: note: or mark surrounding function as 'raises'
def main():
^
mojo: error: failed to parse the provided Mojo source module

The text "42" is a fine number, but Mojo doesn’t look at the value. Int(...) from a string can fail (think of Int("hello")), so it’s marked raises, and main isn’t. The two notes are the two fixes: a try block around the call, or raises on the function.

A context here means the function your code is in. Cannot raise means that function wasn’t declared with raises, so it has promised its callers that it never fails with an error. Calling something that might raise would break that promise.

In Python, any function can raise anything, and you find out at runtime. In Mojo, a plain def doesn’t raise unless it’s marked def name() raises:, so you can see in the signature which calls can fail. The errors page of the Mojo manual describes this model.

Common things that can raise in Mojo 1.2:

Call Why it can fail
Int("42"), Float64("3.5") the text might not be a number
d[key] on a Dict the key might be missing
Python.import_module("numpy") and most Python calls Python code can raise any exception
open("notes.txt", "r") the file might not exist
your own functions marked raises they might raise

If you know what to do when it fails (show a message, use a default, ask again), catch the error where it happens:

def main():
try:
var n = Int("4x2")
print(n)
except e:
print("Not a number:", e)

Output:

Not a number: String is not convertible to integer with base 10: '4x2'

main stays a non-raising function, because no error can escape from it. This is the right fix when bad input is expected, like anything a user types. See Mojo Try/Except.

If this function can’t do anything useful about the error, pass it on to the caller. Add raises to the signature:

def parse_age(text: String) raises -> Int:
return Int(text)
def main() raises:
var age = parse_age("36")
print(age)

Output:

36

raises goes after the arguments and before ->. Notice that main needed it too: once parse_age can raise, every caller has the same choice to make, try or raises. When an error reaches the top of main with nobody catching it, the program stops and prints Unhandled exception caught during execution: followed by the message.

def main() raises: is fine for small programs and experiments. In a real program, handle errors somewhere sensible so a typo in the input doesn’t stop everything.

Some operations have a non-raising twin. For a Dict, d[key] raises when the key is missing, but d.get(key) returns an Optional instead:

def price_of(item: String) -> Int:
var prices: Dict[String, Int] = {"tea": 3, "cake": 5}
return prices.get(item).or_else(0)
def main():
print(price_of("tea"), price_of("pie"))

Output:

3 0

.get(item) gives “a price, or nothing”, and .or_else(0) picks 0 for nothing. No raises anywhere. See Mojo Dictionaries and Mojo Optional.

  • Reading numbers from text: Int(input()), Int(arg), Float64(line).
  • Looking up a dictionary with d[key] inside a helper function.
  • Python interop: almost every call on a PythonObject can raise, so functions that use Python usually end up raises. See Mojo Calling Python.
  • Your own raise: writing raise Error("...") in a function without raises gives a slightly different message, 'raise' requires a surrounding 'try' block or the enclosing function to declare 'raises'. The fixes are the same. See Mojo Errors.

Write to_int(text: String) -> Int that returns the number, or -1 if the text isn’t a number. The function must not be marked raises, and main must not be either.

Hint: put the return Int(text) inside a try, and return -1 in the except.

Show solution
def to_int(text: String) -> Int:
try:
return Int(text)
except:
return -1
def main():
print(to_int("12"))
print(to_int("twelve"))

Output:

12
-1

The try block catches the error inside to_int, so nothing can escape and the function doesn’t need raises. A bare except: is fine when you don’t need the error message.

  • A function that can fail is marked raises, and only raises functions may call it without handling the error.
  • Int(text), d[key], file and Python calls are the usual raising functions.
  • Fix 1: try / except where you can deal with the error.
  • Fix 2: add raises to the function, and then decide again in its caller.
  • Fix 3: use a non-raising version, like d.get(key).or_else(...).

Next up: len(String/StringSlice) is not supported, the error for len(s) on a string.

Quick check

1. Why does Int("42") in a plain def main(): fail to build, even though "42" is a valid number?
2. Where does raises go in a function signature?
3. Which Dict lookup does NOT need raises or try?