An error union holds either an error or a payload value of an inner type. Zig writes the type with `!`, such as `FibonacciError!i32`. A function can name its error set explicitly or let the compiler infer it. section 3.2.2
Errors are values defined by error sets. In the checked Fibonacci function, an input above the limit returns an error; otherwise, the function returns a number. Calls use `try`, `catch`, or an `if` capture to handle the result. section 3.2.2
Listing 3.2 Fibonacci but checked
const FibonacciError = error { OverFibonacciLimit };
const fibonacci_limit = 30;
fn fibonacci(n: usize) FibonacciError!i32 { #1
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else if (n > fibonacci_limit) {
return error.OverFibonacciLimit; #2
}
return try fibonacci(n - 1) + try fibonacci(n - 2); #3
}
The checked Fibonacci function shows an error-union return type, an explicit error set, and a recursive call using `try`. section 3.2.2
Choose how to handle the result:
- Capture success or failure with an `if` expression. section 3.2.2
- Use `catch` to handle an error locally or return it. section 3.2.2
- Use `try` when the call appears inside code that can return the error. section 3.2.2
