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
!Treturns either aTor anerror.Name. try eunwrapse: !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 funwrapse: !T, usingf: Twheneis an error. For a!void, the fallback is an action of typevoid:check() catch log().e catch |err| falso names the error, ananyerror, for the fallback only;|_|discards it, and anerrthe 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!voidruns and then the code after it; for a!Tthere is no value it could give, so it must leave withreturn,breakorcontinueon every path (E118); to give a value per error, call a function:catch |err| fallback_for(err). None of these may be inside adefer(E118).- A
!Tresult cannot be ignored (E113):tryit orcatchit. anyerroris 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!Tis expected, soreturn errreturns it. Errors compare with==and!=;@errorName(err)is the name, such as"NotFound".switch (err)has armserror.Name => { ... }, and since error names are open it must have anelse(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
Tornullfits where a?Tis expected:var best: ?i64 = null, thenbest = 7. A function may return!?T, value or nothing or error: aT,nullanderror.Nameall fit, and the caller writestry f() orelse vorif (try f()) |v| { ... }. e orelse funwrapse: ?T, givingf: Twheneis null (E118 ifeis not an optional). The fallback may instead leave:orelse return(orreturn v),orelse break,orelse continue, or be a block that leaves on every path (orelse { log(); return }, E118); not inside adefer(E118).if (e) |v| { ... }runs the block with the value ofe: ?T, and anyelsewheneis null;while (e) |v| { ... }repeats untileis null, evaluating it each time (E118 ifeis not an optional).vis a constant of typeT, 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; anifwith a value has no capture.e == nullande != nullask whethere: ?Tholds a value, for any T, slices too (null == eas well). Otherwise a?Tcannot be printed or compared: not with aT(opt == 3is E103; unwrap it first), nor with another?T. A?Tresult 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(""))
}