liveBook · Manning

Catch

As explained in Systems Programming with Zig

In Zig, catch is an error-handling expression that evaluates an error-union operand and executes a fallback expression when the operand contains an error.

Zig’s `catch` handles an error-union result: success supplies the payload, while an error selects a fallback expression. Capture the error with `|e|` when the fallback needs it. section 3.2.2

const result = fibonacci(n) catch |e| {
    std.debug.print("failure: {}\n", .{e});
    return;
};

This Fibonacci call captures an error, prints it, and returns from the caller. section 3.2.2

const result = fibonacci(n) catch |e| {
    return e;
};

A shorter fallback returns the captured error to the caller. section 3.2.2

How Systems Programming with Zig covers it

How deep it goes
Shows captured-error fallbacks and return paths alongside definitions of error sets and error unions.
Examples
Uses Fibonacci evaluation to print a failure, return an error, or propagate it with try.
What you can do after
Apply catch to report a Fibonacci error or return it from the caller.
How it connects
Connects error unions and error sets with try and if/else error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.