ZI

Zig Error Handling

Error handling patterns using Zig's error union types

Details

Language / Topic
zigZig
Category
Error Handling

Rules

balanced
- Return error unions (`!T`) from fallible functions and propagate errors with `try` instead of `catch`-and-rethrow boilerplate.
- Define errors in named error sets (`const ParseError = error{ InvalidInput, UnexpectedEof };`) to document the possible failures of a function.
- Use `catch` to provide a fallback value (`const val = fallible() catch defaultValue`) when a default is safe and meaningful.
- Use `catch |err| switch (err) { ... }` for structured error dispatch when different errors require different recovery strategies.
- Use `errdefer` to register cleanup that runs only on error exit paths — it prevents resource leaks without duplicating cleanup logic in every error branch.
- Merge error sets with `error{A, B} || OtherErrorSet` when a function delegates to multiple subsystems that each have their own error set.
- Avoid discarding errors with `_ = fallible() catch {};` — always handle or log the error, even if recovery is not possible.