Skip to content

Mojo Custom Errors

So far every error has been a plain Error with a text message. That’s fine for most programs. But when the caller needs to react differently to different problems, checking message text gets fragile. Mojo lets you define your own error types with real fields, and the compiler then makes sure every caller gets exactly that type. This lesson shows how.

A custom error is just a struct: a type you define, with named fields. (Structs get their own lesson, Mojo Structs. You only need the basics here.)

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def parse_line(line_no: Int, text: String) raises ConfigError -> String:
if "=" not in text:
raise ConfigError(line_no, "missing '='")
return text
def main():
var lines: List[String] = ["name=Ada", "age 36", "city=London"]
for i in range(len(lines)):
try:
_ = parse_line(i + 1, lines[i])
print("line", i + 1, "ok")
except e:
print("line", e.line, "is broken:", e.reason)
print(e)

Output:

line 1 ok
line 2 is broken: missing '='
ConfigError(line=2, reason=missing '=')
line 3 ok

Let’s go through the new parts:

  • struct ConfigError defines the error type, with two fields: line and reason.
  • @fieldwise_init writes the constructor for you, so ConfigError(2, "missing '='") fills in the fields in order.
  • (Copyable, Writable) are traits: promises about what the type can do. Copyable lets the error be copied, Writable lets you print it. You get a default printout like ConfigError(line=2, reason=missing '=') for free.
  • raises ConfigError says “this function can fail, and when it does, the error is a ConfigError”.
  • In except e:, e is a ConfigError, so e.line and e.reason just work. No casting, no checking.

The default printout shows the field names. For a message meant for people, write your own write_to method. print and the “unhandled error” message both use it:

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def write_to(self, mut writer: Some[Writer]):
writer.write("config line ", self.line, ": ", self.reason)
def main() raises:
raise ConfigError(2, "missing '='")

You’ll see:

stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`
Unhandled exception caught during execution: config line 2: missing '='
mojo: error: execution exited with a non-zero result: 1

writer.write(...) takes several values and writes them one after another, like Error(...) does. The Mojo Writable lesson covers it in detail.

A function can declare one error type, and every error it raises must be that type. A plain string doesn’t fit:

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def parse_line(line_no: Int, text: String) raises ConfigError -> String:
if text == "":
raise "empty line"
return text
def main():
try:
_ = parse_line(1, "")
except e:
print(e)
hello.mojo:8:15: error: cannot implicitly convert 'StringLiteral["empty line"]' value to 'ConfigError'
raise "empty line"
^~~~~~~~~~~~
mojo: error: failed to parse the provided Mojo source module

The same goes for calling functions that raise a different type. Int(text) raises a plain Error, so you can’t call it directly inside a raises ConfigError function. Catch it and turn it into your own type instead:

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def read_number(line_no: Int, text: String) raises ConfigError -> Int:
try:
return Int(text)
except e:
raise ConfigError(line_no, String(e))
def main():
try:
print(read_number(1, "42"))
print(read_number(2, "forty"))
except e:
print("line", e.line, "->", e.reason)

Output:

42
line 2 -> String is not convertible to integer with base 10: 'forty'

This “catch and wrap” step is how you build a clean boundary: inside, the code can use anything from the standard library; outside, callers only ever see ConfigError.

main is special: it can only raise plain Error. Try to give it a type and Mojo says so:

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def main() raises ConfigError:
raise ConfigError(1, "empty file")
hello.mojo:6:5: error: 'main()' can only raise 'Error'; remove the explicit error type
def main() raises ConfigError:
^
mojo: error: failed to parse the provided Mojo source module

A plain raises is fine, as you saw above: your typed error passes through, and the program prints its message. The same happens in any function marked plain raises. The error keeps its message, but the compiler forgets the type, so callers lose the fields:

@fieldwise_init
struct ConfigError(Copyable, Writable):
var line: Int
var reason: String
def parse_line(line_no: Int, text: String) raises ConfigError -> String:
if text == "":
raise ConfigError(line_no, "empty line")
return text
def load() raises:
_ = parse_line(4, "")
def main():
try:
load()
except e:
print(e.line)
hello.mojo:18:16: error: 'Error' value has no attribute 'line'
print(e.line)
~^
mojo: error: failed to parse the provided Mojo source module

load says plain raises, so e is just an Error here. Print it and you’ll still see ConfigError(line=4, reason=empty line), but e.line is gone. The fix: write raises ConfigError on load too, all the way up to where you handle it.

A function can only declare one error type. So what if it can fail in different ways, like “not found” and “no permission”? Give your error a code, and named constants for each kind:

@fieldwise_init
struct FileError(Equatable, ImplicitlyCopyable, Writable):
var code: Int
comptime not_found = FileError(code=1)
comptime no_permission = FileError(code=2)
def write_to(self, mut writer: Some[Writer]):
if self.code == 1:
writer.write("FileError: not found")
elif self.code == 2:
writer.write("FileError: no permission")
else:
writer.write("FileError: unknown")
def open_file(path: String) raises FileError -> String:
if path == "":
raise FileError.not_found
if path == "/secret":
raise FileError.no_permission
return "contents of " + path
def main():
for path in ["notes.txt", "", "/secret"]:
try:
print(open_file(path))
except e:
if e == FileError.not_found:
print("Missing file, using defaults.")
elif e == FileError.no_permission:
print("Can't read", path, "->", e)

Output:

contents of notes.txt
Missing file, using defaults.
Can't read /secret -> FileError: no permission

A few new pieces:

  • comptime not_found = FileError(code=1) makes a named constant inside the struct, so you can write FileError.not_found instead of a magic number. (comptime is explained in Mojo Constants.)
  • Equatable lets you compare two errors with ==. Mojo writes the comparison for you because the struct only has simple fields.
  • ImplicitlyCopyable lets the constant be copied without an explicit .copy().

Compare this with the string checks from Mojo Try/Except: a typo in FileError.not_fuond is a compile error, while a typo in msg.startswith("not fuond") quietly never matches.

If each kind of failure needs different fields (say, a path for “not found” but a size and a limit for “too big”), the standard library’s Variant type can combine several error structs into one. The Mojo manual’s section on multiple error conditions shows how.

Use plain Error when… Use your own error type when…
A message is all anyone needs Callers need data, like a line number or code
You’re writing a script or main You’re writing a library other code calls
The caller will just print it and stop The caller will react differently per kind of failure

Most application code is happy with Error. The Mojo manual’s page on typed errors notes one more reason to use your own type: typed errors without heap-allocated fields like String also work on GPUs.

Make an AgeError struct with one field, value: Int, and a write_to that prints invalid age: <value>. Write check_age(age: Int) raises AgeError -> Int that raises it for ages below 0 or above 150. In main, call it with 30 and 200 inside a try, and print e and e.value in except.

Hint: start from the ConfigError example with the custom write_to.

Show solution
@fieldwise_init
struct AgeError(Copyable, Writable):
var value: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("invalid age: ", self.value)
def check_age(age: Int) raises AgeError -> Int:
if age < 0 or age > 150:
raise AgeError(age)
return age
def main():
try:
print(check_age(30))
print(check_age(200))
except e:
print(e)
print("the bad value was", e.value)

Output:

30
invalid age: 200
the bad value was 200

Because check_age says raises AgeError, the e in except is an AgeError, so e.value works.

This program doesn’t compile. Change one line so it prints bad value: -3.

@fieldwise_init
struct RangeError(Copyable, Writable):
var value: Int
def check(x: Int) raises RangeError:
if x < 0:
raise RangeError(x)
def check_all(x: Int) raises:
check(x)
def main():
try:
check_all(-3)
except e:
print("bad value:", e.value)

Hint: what type does e have when the error passes through a plain raises function?

Show solution
@fieldwise_init
struct RangeError(Copyable, Writable):
var value: Int
def check(x: Int) raises RangeError:
if x < 0:
raise RangeError(x)
def check_all(x: Int) raises RangeError:
check(x)
def main():
try:
check_all(-3)
except e:
print("bad value:", e.value)

Output:

bad value: -3

With plain raises, check_all turned the RangeError into a plain Error and the field was gone. raises RangeError keeps the type all the way to main.

  • A custom error is a struct; add Writable so you can print it, and @fieldwise_init for a quick constructor.
  • raises MyError declares the one error type a function raises, and the compiler enforces it.
  • In except e:, e has the declared type, so you can read its fields directly.
  • Errors of another type (like Int()’s Error) must be caught and wrapped in your type.
  • main can only raise plain Error, and a plain raises forgets the type: keep raises MyError all the way up.
  • For several kinds of failure, use one type with named comptime constants and compare with ==.

Next up: debug asserts, for mistakes that should never happen, and why they crash instead of raising.

Quick check

1. What do you need to make a struct usable as an error type?
2. A function is declared raises ParseError. What is e in a caller's except e:?
3. Inside a raises ParseError function, what happens with raise "oops"?
4. Your typed error passes through a function marked plain raises. What does the caller get?