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.
Catching an error
Section titled “Catching an error”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:
Int("thirty")raises an error.- The rest of the
tryblock is skipped, soprint("age is", age)never runs. except e:runs, with the error stored ine. You can printedirectly.- After the
exceptblock, the program carries on as normal.
Notice that main doesn’t need raises anymore. The error is handled inside it, so nothing can escape.
Keep going after a bad value
Section titled “Keep going after a bad value”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: xskipping:total: 42This 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.
One except, no error types
Section titled “One except, no error types”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 moduleSo 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_7No such user, showing a guest page.Something else went wrong: invalid id: -1Checking 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.
else: only when nothing failed
Section titled “else: only when nothing failed”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 12success, saving itbad input: twelveWhy 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.
finally: always runs
Section titled “finally: always runs”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 12finished with 12bad input: twelvefinished with twelveYou 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 fileclosing the filemain caught: disk is fullAnd 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 5positiveThe 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.
Variables inside try
Section titled “Variables inside try”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 moduleCreate 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:
0var 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.
Re-raising an error
Section titled “Re-raising an error”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") raiseYou’ll see:
log: parsing failedstack 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: 1raise 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.
Only wrap code that can raise
Section titled “Only wrap code that can raise”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 2mojo: error: execution crashedCheck the index yourself (if i < len(xs):) instead. Mojo Debug Asserts explains crashes like this one.
Practice
Section titled “Practice”1. Default to zero
Section titled “1. Default to zero”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:
420-8Because the error is handled inside the function, it doesn’t need raises, and callers don’t need try.
2. Count the good and the bad
Section titled “2. Count the good and the bad”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 oftryis skipped andexceptruns. except e:gives you the error;except:ignores it.String(e)turns it into text.- A
tryhas oneexcept, and you can’t writeexcept ValueError as e:. elseruns only on success;finallyruns every time, even afterreturnor an unhandled error.- Variables made inside
tryvanish after it: declare them before thetry. - Use
raiseinsideexceptto pass the error on, or raise a new error with more context. tryonly 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Errors, error handling, and context managers: the official guide, with a full
try/except/else/finallyexample. - Compound statements reference: the exact rules for
trystatements. Errorin the standard library: what you get ine, and how to turn it into aString.- Mojo tips for Python developers: more places where Python habits need a small change.