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.
The error message
Section titled “The error message”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 moduleThe 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.
What it means
Section titled “What it means”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 |
How to fix it
Section titled “How to fix it”Fix 1: Handle the error with try / except
Section titled “Fix 1: Handle the error with try / except”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.
Fix 2: Mark the function raises
Section titled “Fix 2: Mark the function raises”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:
36raises 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.
Fix 3: Use a version that can’t fail
Section titled “Fix 3: Use a version that can’t fail”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.
Where you’ll usually see it
Section titled “Where you’ll usually see it”- 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
PythonObjectcan raise, so functions that use Python usually end upraises. See Mojo Calling Python. - Your own
raise: writingraise Error("...")in a function withoutraisesgives 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.
Related errors
Section titled “Related errors”- cannot implicitly convert ‘X’ value to ‘Y’:
Int(x)on a number doesn’t raise; only text needs this. - use of unknown declaration ‘x’: a variable created inside
try:doesn’t exist after the block. - All Mojo error pages: the full list.
Practice
Section titled “Practice”1. A safe parser
Section titled “1. A safe parser”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-1The 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 onlyraisesfunctions may call it without handling the error. Int(text),d[key], file and Python calls are the usual raising functions.- Fix 1:
try/exceptwhere you can deal with the error. - Fix 2: add
raisesto 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Errors, error handling, and context managers: the official guide to
raises,raise,tryandexcept. - Mojo tips for Python devs: why error propagation is explicit in Mojo.
- Functions in the Mojo manual: function signatures, including
raises. - Mojo Try/Except: our lesson on catching errors.