Mojo Errors
Programs run into problems all the time: a file is missing, a user types “abc” where you wanted a number, a value is out of range. In Mojo, a function reports a problem like that by raising an error. This page shows how to raise one, how the raises keyword works, and what you see when an error reaches the top of your program. Catching errors with try and except comes in the next lesson.
Your first error
Section titled “Your first error”Here’s a function that refuses a negative age:
def check_age(age: Int) raises -> Int: if age < 0: raise Error("age can't be negative") return age
def main() raises: print(check_age(30)) print(check_age(-5)) print("never printed")When you run it, you see:
30stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: age can't be negativemojo: error: execution exited with a non-zero result: 1Three new things are going on:
raise Error("...")stops the function right there and sends an error back to whoever called it. The text is the error message.raisesin the signature (def check_age(age: Int) raises -> Int) says “this function can fail”. It goes before the->.mainalso saysraises, so it’s allowed to let the error pass through. Nobody catches it, so the program stops, prints the message and exits with code1. The lastprintnever runs.
The first line of that output is a hint, not part of your error. We’ll come back to stack traces at the end of this page.
A shorter way to write it
Section titled “A shorter way to write it”raise with a plain string does the same thing. Mojo wraps the string in an Error for you:
def check_name(name: String) raises -> String: if name == "": raise "name can't be empty" return name
def main() raises: print(check_name("Ada")) print(check_name(""))You’ll see:
Adastack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: name can't be emptymojo: error: execution exited with a non-zero result: 1Use whichever you like. raise Error(...) makes it obvious that you’re creating an error, and it has one extra trick, shown next.
Building a message from several values
Section titled “Building a message from several values”Error(...) takes several values, like print does, and glues them together into one message (without spaces, so add them yourself):
def divide(a: Int, b: Int) raises -> Int: if b == 0: raise Error("can't divide ", a, " by zero") return a // b
def main() raises: print(divide(10, 2)) print(divide(7, 0))You’ll see:
5stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: can't divide 7 by zeromojo: error: execution exited with a non-zero result: 1A good error message says what went wrong and which value caused it. “can’t divide 7 by zero” helps far more than “bad input”.
raises is a promise the compiler checks
Section titled “raises is a promise the compiler checks”In Python, any function can raise anything. In Mojo, a def function can’t raise unless it says raises. Forget it, and the program doesn’t compile:
def check_age(age: Int) -> Int: if age < 0: raise "age can't be negative" return age
def main(): print(check_age(30))hello.mojo:3:9: error: 'raise' requires a surrounding 'try' block or the enclosing function to declare 'raises' raise "age can't be negative" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~mojo: error: failed to parse the provided Mojo source moduleThe same rule applies to callers. If you call a raising function, you either handle the error (with try, next lesson) or mark your own function raises too:
def check_age(age: Int) raises -> Int: if age < 0: raise "age can't be negative" return age
def main(): print(check_age(30))hello.mojo:7:20: error: cannot call function that may raise in a context that cannot raise print(check_age(30)) ~~~~~~~~~^~~~hello.mojo:7:20: note: try surrounding the call in a 'try' block print(check_age(30)) ^hello.mojo:6:5: note: or mark surrounding function as 'raises'def main(): ^mojo: error: failed to parse the provided Mojo source moduleThe compiler even lists both fixes. This is a good thing: just by reading a signature, you know whether a call can fail.
Errors travel up the call chain
Section titled “Errors travel up the call chain”When a function doesn’t handle an error, it passes it to its caller, and so on, until something handles it or it reaches main. Every function along the way must say raises:
def read_setting(name: String) raises -> Int: if name != "port": raise Error("unknown setting: ", name) return 8080
def load_config() raises -> Int: var port = read_setting("prot") print("this line is skipped") return port
def main() raises: print("starting") var port = load_config() print("port is", port)You’ll see:
startingstack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: unknown setting: protmojo: error: execution exited with a non-zero result: 1The typo "prot" makes read_setting raise. load_config doesn’t handle it, so it stops too (its print is skipped), and so does main. Only the message tells you what went wrong, so make it specific.
The standard library raises too
Section titled “The standard library raises too”Many standard library functions can fail, so they’re marked raises. You’ve already met some:
| Call | Raises when |
|---|---|
Int("abc") |
the text isn’t a whole number |
Float64("x1.5") |
the text isn’t a number |
my_dict["missing"] |
the key isn’t in the dictionary (see Mojo Dictionaries) |
"{} {}".format(...) on a String variable |
the placeholders don’t match |
Here’s the first one reaching main:
def main() raises: var n = Int("42") print(n + 1) var m = Int("forty-two") print(m + 1)You’ll see:
43stack 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: 'forty-two'mojo: error: execution exited with a non-zero result: 1The Mojo Type Conversion lesson shows how to read numbers from text safely.
Getting a stack trace
Section titled “Getting a stack trace”The message tells you what failed, not where. For that you want a stack trace: the list of function calls that led to the error. Mojo doesn’t collect one by default, because it costs time and memory. That’s what the hint line at the top of the output was about.
To get a useful one, build your program with debug info (-g) and run it with the MODULAR_DEBUG environment variable set:
def load_config() raises: raise Error("config file is missing")
def start() raises: load_config()
def main() raises: start()With a plain mojo run trace.mojo, you only get the message:
stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: config file is missingmojo: error: execution exited with a non-zero result: 1Now build it with debug info and turn stack traces on:
mojo build -g trace.mojoMODULAR_DEBUG=stack-trace-on-error ./traceHere’s the useful part of what we got on Linux (paths shortened, a few system lines cut):
#2 0x... std::builtin::error::StackTrace::collect_if_enabled(...) Mojo/stdlib/std/builtin/error.mojo:99:22#3 0x... trace::load_config() trace.mojo:2:5#4 0x... trace::start() trace.mojo:5:16#5 0x... trace::main() trace.mojo:8:10...
Unhandled exception caught during execution: config file is missingRead it from the bottom up: main (line 8) called start (line 5), which called load_config, which raised on line 2. With mojo run instead of a built program you only get raw addresses, so use mojo build -g when you need the trace. The Mojo Debugging lesson has more ways to find bugs.
Errors are not crashes
Section titled “Errors are not crashes”An error is something your program expects might happen and can deal with: bad input, a missing file. Some mistakes aren’t like that. Reading xs[10] from a 3-item list, for example, doesn’t raise an error. It stops the program with a crash, and try can’t catch it. That difference is the topic of Mojo Debug Asserts.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Raise an error | raise ValueError("bad") |
raise Error("bad") or raise "bad" |
| Error types | Many built-in classes (ValueError, KeyError…) |
One general type, Error, plus your own (Mojo Custom Errors) |
| Which functions can raise | Any of them | Only those marked raises |
| Forgetting to handle an error | Crashes at run time, maybe much later | Compile error, right away |
| Uncaught error | Traceback, exit code 1 | Message, exit code 1, trace only if you ask |
ValueError doesn’t exist in Mojo: raise ValueError("bad") gives “use of unknown declaration ‘ValueError’”.
Practice
Section titled “Practice”1. Reject bad percentages
Section titled “1. Reject bad percentages”Write check_percent(p: Int) raises -> Int that returns p if it’s between 0 and 100, and otherwise raises an error whose message includes the value, like percent must be 0 to 100, got 150. Call it with 75 and then 150 from main.
Hint: use raise Error("...", p) so the value ends up in the message.
Show solution
def check_percent(p: Int) raises -> Int: if p < 0 or p > 100: raise Error("percent must be 0 to 100, got ", p) return p
def main() raises: print(check_percent(75)) print(check_percent(150))You’ll see:
75stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: percent must be 0 to 100, got 150mojo: error: execution exited with a non-zero result: 1Both check_percent and main need raises: one raises the error, the other lets it pass through.
2. Fix the compile error
Section titled “2. Fix the compile error”This program doesn’t compile. Make it compile without changing parse_score.
def parse_score(text: String) raises -> Int: return Int(text)
def report(text: String): print("score:", parse_score(text))
def main(): report("17")Hint: the error is in report. Which functions call something that can raise?
Show solution
def parse_score(text: String) raises -> Int: return Int(text)
def report(text: String) raises: print("score:", parse_score(text))
def main() raises: report("17")Output:
score: 17report calls a raising function, so it needs raises. That makes report a raising function too, so main needs raises as well. In the next lesson you’ll stop the chain with try instead.
- A function reports a problem with
raise Error("message")(or justraise "message"). - A function can only raise if its signature says
raises, before the->. The compiler checks this. - Calling a raising function means you either handle the error or mark your function
raisestoo. - An unhandled error travels up to
mainand stops the program with its message and exit code 1. Error(...)joins several values into one message: include the value that caused the problem.- For a stack trace, build with
mojo build -gand run withMODULAR_DEBUG=stack-trace-on-error.
Next up: try/except, how to catch an error and keep your program running.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Errors, error handling, and context managers: the official guide to raising and handling errors, including stack traces.
Errorin the standard library: theErrortype, its constructors andget_stack_trace().- Compound statements reference: the exact rules for
raiseandtry. mojo buildreference: the-g(debug info) option used for stack traces.