NI

Nim Error Handling

Error handling in Nim using exceptions, Result types, and the raises pragma

Details

Language / Topic
nimNim
Category
Error Handling

Rules

balanced
- Define custom exception types by inheriting from `CatchableError` for recoverable errors and `Defect` for programmer errors — never raise `Defect` subclasses in library code.
- Use `{.raises: [MyError, IOError].}` on public procedures to document and enforce the exception contract — the compiler verifies the annotation exhaustively.
- Use `try: ... except MyError as e: echo e.msg` for structured exception handling — avoid bare `except:` which silently catches `Defect` subclasses.
- Use the `results` package (`Result[T, E]`) for functions where errors are expected and callers must handle them explicitly without using exceptions.