Skip to content

Mojo Try/Except

In the last lesson every error stopped the program. Most of the time you’d rather deal with it: show a friendly message, skip a bad line, use a default value. That’s what try and except are for. If you know Python, this will look very familiar, with a couple of differences that we’ll point out.

Put the code that might fail in a try block. If it raises, Mojo jumps to the except block:

def main():
try:
var age = Int("thirty")
print("age is", age)
except e:
print("That's not a number:", e)
print("The program keeps going.")

Output:

That's not a number: String is not convertible to integer with base 10: 'thirty'
The program keeps going.

Here’s what happens, step by step:

  1. Int("thirty") raises an error.
  2. The rest of the try block is skipped, so print("age is", age) never runs.
  3. except e: runs, with the error stored in e. You can print e directly.
  4. After the except block, the program carries on as normal.

Notice that main doesn’t need raises anymore. The error is handled inside it, so nothing can escape.

A common pattern: loop over some input, handle the bad items and keep the good ones:

def main():
var inputs: List[String] = ["10", "x", "25", "", "7"]
var total = 0
for text in inputs:
try:
total += Int(text)
except:
print("skipping:", text)
print("total:", total)

Output:

skipping: x
skipping:
total: 42

This time it’s just except: with no name. Use that when you don’t need the error itself. The empty string "" fails too, which is why there’s a second “skipping” line with nothing after it.

Here’s the biggest difference from Python. In Python you can write several except clauses, one per exception type:

try:
...
except ValueError as e:
...
except KeyError as e:
...

Mojo doesn’t have that. A try gets one except, and you don’t name a type:

def main():
try:
var n = Int("abc")
print(n)
except ValueError as e:
print(e)
hello.mojo:5:23: error: expected ':' after 'except'
except ValueError as e:
^
mojo: error: failed to parse the provided Mojo source module

So how do you tell different problems apart? With plain Error, you look at the message. String(e) turns the error into a String you can check:

def load_user(id: Int) raises -> String:
if id < 0:
raise Error("invalid id: ", id)
if id > 100:
raise Error("user not found: ", id)
return String("user_", id)
def main():
for id in [7, 500, -1]:
try:
print(load_user(id))
except e:
var msg = String(e)
if msg.startswith("user not found"):
print("No such user, showing a guest page.")
else:
print("Something else went wrong:", msg)

Output:

user_7
No such user, showing a guest page.
Something else went wrong: invalid id: -1

Checking message text works for small programs, but it’s fragile: change the wording and the check breaks. When you need to tell errors apart reliably, give them their own type. That’s the topic of Mojo Custom Errors.

An else block after except runs only if the try block finished without an error:

def main():
for text in ["12", "twelve"]:
try:
var n = Int(text)
print("parsed", n)
except:
print("bad input:", text)
else:
print("success, saving it")

Output:

parsed 12
success, saving it
bad input: twelve

Why not just put print("success, saving it") at the end of the try block? You could. But code in try is code whose errors you’re catching. Keeping the “after success” work in else makes it clear which line you expected to fail, and stops your except from accidentally catching errors from the wrong place.

A finally block runs at the end no matter what: after success, after an error, even after a return. It’s the place for clean-up work, like closing a file or printing “done”:

def parse(text: String):
try:
var n = Int(text)
print("parsed", n)
except:
print("bad input:", text)
finally:
print("finished with", text)
def main():
parse("12")
parse("twelve")

Output:

parsed 12
finished with 12
bad input: twelve
finished with twelve

You can also use finally without except. Then the error isn’t handled: the clean-up runs, and the error keeps travelling up to the caller:

def save() raises:
try:
print("opening the file")
raise "disk is full"
finally:
print("closing the file")
def main():
try:
save()
except e:
print("main caught:", e)

Output:

opening the file
closing the file
main caught: disk is full

And finally even runs when the try block returns:

def sign(x: Int) -> String:
try:
if x > 0:
return "positive"
return "zero or negative"
finally:
print("checked", x)
def main():
print(sign(5))

Output:

checked 5
positive

The full order is try, then except (only on error) or else (only on success), then finally (always). You need at least an except or a finally. The Mojo manual’s page on errors puts all four blocks together in one example.

A variable created inside the try block only exists there. This doesn’t compile:

def main():
try:
var n = Int("5")
except e:
print(e)
print(n)
hello.mojo:6:11: error: use of unknown declaration 'n'
print(n)
^
mojo: error: failed to parse the provided Mojo source module

Create the variable before the try, then give it a value in both branches:

def main():
var n: Int
try:
n = Int("5x")
except:
n = 0
print(n)

Output:

0

var n: Int declares n without a value. Mojo checks that every path gives it one before it’s used, and here both the try and the except do.

Sometimes you want to notice an error (say, to log it) but still let it go up to the caller. Write raise on its own inside except:

def main() raises:
try:
var n = Int("abc")
print(n)
except e:
print("log: parsing failed")
raise

You’ll see:

log: parsing failed
stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: String is not convertible to integer with base 10: 'abc'
mojo: error: execution exited with a non-zero result: 1

raise e works too. Often it’s even better to raise a new error that says more about what you were doing, with the original message inside:

def read_port(text: String) raises -> Int:
try:
return Int(text)
except e:
raise Error("bad port setting '", text, "': ", e)
def main():
try:
print(read_port("80a"))
except e:
print(e)

Output:

bad port setting '80a': String is not convertible to integer with base 10: '80a'

Now the message says both what went wrong and where: someone reading it knows to look at the port setting.

If nothing inside a try can raise, Mojo warns you that the except is pointless. This matters because some mistakes, like reading past the end of a list, aren’t errors at all. They crash the program, and try can’t catch them:

def main():
var xs: List[Int] = [1, 2, 3]
var i = 5
try:
print(xs[i])
except e:
print("caught:", e)
hello.mojo:7:15: warning: 'except' logic is unreachable, try doesn't raise an exception
print("caught:", e)
^
hello.mojo:6:12: warning: variable 'e' was never used, remove it?
except e:
^
At: hello.mojo:5:17: Assert Error: index 5 is out of bounds, valid range is 0 to 2
mojo: error: execution crashed

Check the index yourself (if i < len(xs):) instead. Mojo Debug Asserts explains crashes like this one.

Write to_int_or_zero(text: String) -> Int (no raises!) that returns the number in text, or 0 if it isn’t a number. Print the result for "42", "4 2" and "-8".

Hint: return from inside try, and return 0 from except.

Show solution
def to_int_or_zero(text: String) -> Int:
try:
return Int(text)
except:
return 0
def main():
print(to_int_or_zero("42"))
print(to_int_or_zero("4 2"))
print(to_int_or_zero("-8"))

Output:

42
0
-8

Because the error is handled inside the function, it doesn’t need raises, and callers don’t need try.

Given var lines: List[String] = ["3", "x", "5", "y", "z"], count how many lines are numbers and how many aren’t, using else for the good ones. Print good: 2 bad: 3.

Hint: add to good in else, and to bad in except.

Show solution
def main():
var lines: List[String] = ["3", "x", "5", "y", "z"]
var good = 0
var bad = 0
for line in lines:
try:
_ = Int(line)
except:
bad += 1
else:
good += 1
print("good:", good, "bad:", bad)

Output:

good: 2 bad: 3

_ = Int(line) throws the number away: we only care whether it parsed. Without the _ =, Mojo would warn that the value is unused.

  • Put code that might fail in try; when it raises, the rest of try is skipped and except runs.
  • except e: gives you the error; except: ignores it. String(e) turns it into text.
  • A try has one except, and you can’t write except ValueError as e:.
  • else runs only on success; finally runs every time, even after return or an unhandled error.
  • Variables made inside try vanish after it: declare them before the try.
  • Use raise inside except to pass the error on, or raise a new error with more context.
  • try only catches raised errors, not crashes like an out-of-range index.

Next up: custom errors, how to give your errors their own type and fields.

Quick check

1. How many except clauses can one try have in Mojo?
2. When does an else block after try/except run?
3. A try block has finally but no except, and the code inside raises. What happens?
4. Why does print(n) after a try fail when n was created with var n = ... inside the try?