liveBook · Manning

Try

As explained in Systems Programming with Zig

In Zig, try is an error-propagation operator that returns an error from the enclosing function when its error-union operand contains an error.

Zig’s `try` operates on an error-union value. If it contains an error, `try` returns that error from the enclosing function; otherwise, the expression yields the payload. It propagates errors rather than handling them with a catch block. 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 uses `try` on recursive calls, propagating their errors while adding their successful values. section 3.2.2

Listing 3.7 Cat with arguments and more files
const std = @import("std");

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena); #1
    const cwd = std.Io.Dir.cwd();

    const stdout_file = std.Io.File.stdout();
    var stdout_buffer: [1024]u8 = undefined;
    var stdout_writer = stdout_file.writer(io, &stdout_buffer);
    const stdout = &stdout_writer.interface;

    for (args[1..]) |filepath| { #2
        const text = try cwd.readFileAlloc(
            filepath,
            io,
            arena,
            .unlimited,
        );
        try stdout.writeAll(text);
    }

    try stdout.flush(); #3
}

The file-concatenation program uses `try` for argument conversion, file reads, output writes, and flushing. section 3.3.2

How Systems Programming with Zig covers it

How deep it goes
Defines error sets and error unions, then demonstrates propagation and contrasts `try` with `catch` and `if` handling.
Examples
Uses checked recursive Fibonacci and a command-line file-concatenation program.
What it assumes
Builds from error sets through error unions before introducing `try`.
What you can do after
Apply Zig’s `try` operator to propagate errors from function calls and I/O operations.
How it connects
Links error propagation to error sets, error unions, `catch`, and `if`/`else` 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.