Version: 1.1.0

Errors and context managers

Mojo reports failure as a value, not a hidden exception path you can ignore. A function that fails is marked raises, and callers must handle it.

Essentials

  • Add raises to the signature when the function can fail.
  • try / except handles the error. except e captures it.
  • raise Error("message") creates a failure.
  • A with statement calls enter and exit methods, the same idea as a Python context manager.
  • A raises parameter lets higher-order functions forward the failure of a callback.

Example

def parse(text: String) raises -> Int:
    if not text:
        raise Error("empty")
    return atol(text)

def main() raises:
    print(parse("42"))

Keep in mind

Handle errors at the boundary that knows what to do. Do not swallow them in a bare except just to keep a signature quiet.