Spec chapters

13. Errors

Errors are values. !T holds either a T or an error; error.Name is an error (names are global, and need no declaration).

  • A function returning !T returns either a T or an error.Name.
  • try e unwraps e: !T: on an error, the current function returns that error at once. It is allowed only in a function that returns !U (E118).
  • e catch f unwraps e: !T, using f: T when e is an error. For a !void, the fallback is an action of type void: check() catch log().
  • e catch |err| f also names the error, an anyerror, for the fallback only; |_| discards it, and an err the fallback never uses is E110. The fallback of a catch may instead leave (catch return, catch |err| return err, catch break, catch continue), or be a block. A block for a !void runs and then the code after it; for a !T there is no value it could give, so it must leave with return, break or continue on every path (E118); to give a value per error, call a function: catch |err| fallback_for(err). None of these may be inside a defer (E118).
  • A !T result cannot be ignored (E113): try it or catch it.
  • anyerror is the type of an error. It is an ordinary value type: it can be stored, passed and returned (var last: anyerror = error.None), and it fits where a !T is expected, so return err returns it. Errors compare with == and !=; @errorName(err) is the name, such as "NotFound". switch (err) has arms error.Name => { ... }, and since error names are open it must have an else (E127); an error arm has no payload.
// expect: 0: Zero
// expect: -3: negative
// expect: 4 = 4
uses io

fn check(x: i64) !i64 {
    if (x == 0) {
        return error.Zero
    }
    if (x < 0) {
        return error.Neg
    }
    return x
}

fn explain(e: anyerror) str {
    switch (e) {
        error.Neg => { return "negative" }
        else => { return @errorName(e) }
    }
}

fn main(io: Io) void {
    const xs = [_]i64{ 0, -3, 4 }
    for (xs) |x| {
        const v = check(x) catch |e| {
            io.print(x, ": ", explain(e))
            continue
        }
        io.print(x, " = ", v)
    }
}

?T holds either a T or null, as in Zig. T may be any value type but !U (E108). T may itself be optional or a pointer, which can already be null: a ??U or ?*U has two levels, null or a value that may be null. They come from generic code: a ?V with V = ?i64, so get on a HashMap(i64, ?i64) tells a missing key (null) from a null value. null is the outer level; a plain value is wrapped in every level (const x: ??i64 = 7); each orelse or capture unwraps one. An owned ?U is unwrapped where it is made, so it is never wrapped again (??Buf(u8) is E133).

  • A T or null fits where a ?T is expected: var best: ?i64 = null, then best = 7. A function may return !?T, value or nothing or error: a T, null and error.Name all fit, and the caller writes try f() orelse v or if (try f()) |v| { ... }.
  • e orelse f unwraps e: ?T, giving f: T when e is null (E118 if e is not an optional). The fallback may instead leave: orelse return (or return v), orelse break, orelse continue, or be a block that leaves on every path (orelse { log(); return }, E118); not inside a defer (E118).
  • if (e) |v| { ... } runs the block with the value of e: ?T, and any else when e is null; while (e) |v| { ... } repeats until e is null, evaluating it each time (E118 if e is not an optional). v is a constant of type T, known only in that block. An owned value belongs to the block, which must free or move it (E135), so these work on an owned ?T: while (a.pop(&bufs)) |b| { ... }. They are statements; an if with a value has no capture.
  • e == null and e != null ask whether e: ?T holds a value, for any T, slices too (null == e as well). Otherwise a ?T cannot be printed or compared: not with a T (opt == 3 is E103; unwrap it first), nor with another ?T. A ?T result cannot be ignored (E113). An owned one (?Buf(u8), ?Db) must be unwrapped right away, like an owned !T (E133), so it cannot be compared with null either.
// expect: 4
// expect: -1
// expect: 9
// expect: true false
uses io

fn first(xs: []i64) ?i64 {
    if (@len(xs) == 0) {
        return null
    }
    return xs[0]
}

fn main(io: Io) void {
    io.print(first([2]i64{ 4, 5 }[0..]) orelse -1)
    var best: ?i64 = null
    io.print(best orelse -1)
    best = 9
    io.print(best orelse -1)
    io.print(best != null, " ", first([1]i64{ 3 }[1..]) != null)
}
// expect: 42
// expect: -1
// fails: Empty
uses io

fn parse_digit(c: u8) !i64 {
    if (c < 48 or c > 57) {
        return error.NotADigit
    }
    return @as(i64, c - 48)
}

fn parse(s: str) !i64 {
    if (@len(s) == 0) {
        return error.Empty
    }
    var n = 0
    for (s) |c| {
        n = n * 10 + try parse_digit(c)
    }
    return n
}

fn main(io: Io) !void {
    io.print(try parse("42"))
    io.print(parse("4x") catch -1)
    io.print(try parse(""))
}