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.
An error with fields
Section titled “An error with fields”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_initstruct 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 okline 2 is broken: missing '='ConfigError(line=2, reason=missing '=')line 3 okLet’s go through the new parts:
struct ConfigErrordefines the error type, with two fields:lineandreason.@fieldwise_initwrites the constructor for you, soConfigError(2, "missing '='")fills in the fields in order.(Copyable, Writable)are traits: promises about what the type can do.Copyablelets the error be copied,Writablelets youprintit. You get a default printout likeConfigError(line=2, reason=missing '=')for free.raises ConfigErrorsays “this function can fail, and when it does, the error is aConfigError”.- In
except e:,eis aConfigError, soe.lineande.reasonjust work. No casting, no checking.
A nicer message
Section titled “A nicer message”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_initstruct 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: 1writer.write(...) takes several values and writes them one after another, like Error(...) does. The Mojo Writable lesson covers it in detail.
The compiler checks the error type
Section titled “The compiler checks the error type”A function can declare one error type, and every error it raises must be that type. A plain string doesn’t fit:
@fieldwise_initstruct 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 moduleThe 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_initstruct 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:
42line 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.
Typed errors and main
Section titled “Typed errors and main”main is special: it can only raise plain Error. Try to give it a type and Mojo says so:
@fieldwise_initstruct 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 typedef main() raises ConfigError: ^mojo: error: failed to parse the provided Mojo source moduleA 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_initstruct 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 moduleload 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.
Several kinds of failure in one type
Section titled “Several kinds of failure in one type”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_initstruct 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.txtMissing file, using defaults.Can't read /secret -> FileError: no permissionA few new pieces:
comptime not_found = FileError(code=1)makes a named constant inside the struct, so you can writeFileError.not_foundinstead of a magic number. (comptimeis explained in Mojo Constants.)Equatablelets you compare two errors with==. Mojo writes the comparison for you because the struct only has simple fields.ImplicitlyCopyablelets 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.
Error or your own type?
Section titled “Error or your own type?”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.
Practice
Section titled “Practice”1. An age error
Section titled “1. An age error”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_initstruct 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:
30invalid age: 200the bad value was 200Because check_age says raises AgeError, the e in except is an AgeError, so e.value works.
2. Fix the lost field
Section titled “2. Fix the lost field”This program doesn’t compile. Change one line so it prints bad value: -3.
@fieldwise_initstruct 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_initstruct 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: -3With 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
Writableso you can print it, and@fieldwise_initfor a quick constructor. raises MyErrordeclares the one error type a function raises, and the compiler enforces it.- In
except e:,ehas the declared type, so you can read its fields directly. - Errors of another type (like
Int()’sError) must be caught and wrapped in your type. maincan only raise plainError, and a plainraisesforgets the type: keepraises MyErrorall the way up.- For several kinds of failure, use one type with named
comptimeconstants and compare with==.
Next up: debug asserts, for mistakes that should never happen, and why they crash instead of raising.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Typed errors (Mojo manual): defining, raising and catching your own error types.
- Representing multiple error conditions: error codes and the
Variantapproach. Writabletrait: whatwrite_toneeds, so your errors print nicely.@fieldwise_initdecorator: the constructor it writes for you.