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
raisesto the signature when the function can fail. try/excepthandles the error.except ecaptures it.raise Error("message")creates a failure.- A
withstatement calls enter and exit methods, the same idea as a Python context manager. - A
raisesparameter 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.