Skip to content

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.

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:

30
stack 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 negative
mojo: error: execution exited with a non-zero result: 1

Three 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.
  • raises in the signature (def check_age(age: Int) raises -> Int) says “this function can fail”. It goes before the ->.
  • main also says raises, so it’s allowed to let the error pass through. Nobody catches it, so the program stops, prints the message and exits with code 1. The last print never 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.

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:

Ada
stack 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 empty
mojo: error: execution exited with a non-zero result: 1

Use whichever you like. raise Error(...) makes it obvious that you’re creating an error, and it has one extra trick, shown next.

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:

5
stack 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 zero
mojo: error: execution exited with a non-zero result: 1

A good error message says what went wrong and which value caused it. “can’t divide 7 by zero” helps far more than “bad input”.

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 module

The 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 module

The compiler even lists both fixes. This is a good thing: just by reading a signature, you know whether a call can fail.

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:

starting
stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: unknown setting: prot
mojo: error: execution exited with a non-zero result: 1

The 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.

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:

43
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: 'forty-two'
mojo: error: execution exited with a non-zero result: 1

The Mojo Type Conversion lesson shows how to read numbers from text safely.

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 missing
mojo: error: execution exited with a non-zero result: 1

Now build it with debug info and turn stack traces on:

Terminal window
mojo build -g trace.mojo
MODULAR_DEBUG=stack-trace-on-error ./trace

Here’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 missing

Read 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.

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.

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’”.

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:

75
stack 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 150
mojo: error: execution exited with a non-zero result: 1

Both check_percent and main need raises: one raises the error, the other lets it pass through.

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: 17

report 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 just raise "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 raises too.
  • An unhandled error travels up to main and 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 -g and run with MODULAR_DEBUG=stack-trace-on-error.

Next up: try/except, how to catch an error and keep your program running.

Quick check

1. What does raises in def load() raises -> String: mean?
2. A function without raises contains raise "oops". What happens?
3. An error reaches main, and main is marked raises. What does the program do?
4. What does raise Error("got ", 5, " items") use as its message?