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
