Skip to content

Errors are values

20 January 2025 ยท Zig 0.13

Zig has no exceptions. A function that can fail says so in its return type, an error union: ParseError!u8 is either one of the errors in ParseError or a u8, and the caller has to deal with the error, if only by passing it on.

const std = @import("std");

const ParseError = error{ Empty, NotADigit };

fn digit(c: u8) ParseError!u8 {
    return switch (c) {
        '0'...'9' => c - '0',
        else => error.NotADigit,
    };
}

fn sumDigits(s: []const u8) ParseError!u32 {
    if (s.len == 0) return error.Empty;
    var total: u32 = 0;
    for (s) |c| total += try digit(c);
    return total;
}

test "sum the digits" {
    try std.testing.expectEqual(@as(u32, 6), try sumDigits("123"));
    try std.testing.expectError(error.NotADigit, sumDigits("12a"));
    try std.testing.expectError(error.Empty, sumDigits(""));
}

try is shorthand for passing the error on: try digit(c) means digit(c) catch |err| return err. Where an error can be handled, catch handles it in place:

test "or fall back to a default" {
    const n = sumDigits("x") catch 0;
    try std.testing.expectEqual(@as(u32, 0), n);
}

errdefer runs only when the function returns an error, which is exactly what a half-built result wants: the happy path keeps what it built, the failing one frees it.

fn digits(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
    const out = try allocator.alloc(u8, s.len);
    errdefer allocator.free(out);
    for (s, out) |c, *d| d.* = try digit(c);
    return out;
}

test "nothing leaks on the way out" {
    const allocator = std.testing.allocator;
    const ds = try digits(allocator, "42");
    defer allocator.free(ds);
    try std.testing.expectEqualSlices(u8, &.{ 4, 2 }, ds);
    try std.testing.expectError(error.NotADigit, digits(allocator, "4x"));
}

std.testing.allocator fails the test if anything it handed out wasn't freed, so the second expectError is also checking the errdefer.