Zig Errors & Error Unions
Things go wrong: files are missing, input is malformed, memory runs out. Zig handles failure with errors as values. A function that can fail returns an error union — either an error or a normal result — and the compiler refuses to let you use the result without deciding what to do about the error. There are no exceptions, so nothing can jump past your code invisibly.
Error sets
An error set is a list of named errors, a bit like an enum:
const ParseError = error{ Empty, TooLong, NotANumber };Each error is a value such as error.Empty (or ParseError.Empty).
Error unions
ParseError!u32 means "either an error from ParseError, or a u32". A function returns errors with return error.Something, and success values with a plain return:
const std = @import("std");
const AgeError = error{ Negative, TooOld };
fn checkAge(age: i32) AgeError!u8 {
if (age < 0) return error.Negative;
if (age > 150) return error.TooOld;
return @intCast(age);
}
pub fn main() void {
const inputs = [_]i32{ 34, -2, 200 };
for (inputs) |a| {
if (checkAge(a)) |age| {
std.debug.print("{d}: valid age {d}\n", .{ a, age });
} else |err| {
std.debug.print("{d}: rejected ({t})\n", .{ a, err });
}
}
}34: valid age 34
-2: rejected (Negative)
200: rejected (TooOld)
catch: handle it here
expr catch fallback unwraps the value, or uses fallback if there was an error. You can capture the error too, and run a whole block:
const std = @import("std");
pub fn main() void {
const a = std.fmt.parseInt(u32, "120", 10) catch 0;
const b = std.fmt.parseInt(u32, "12o", 10) catch 0;
std.debug.print("a={d} b={d}\n", .{ a, b });
const c = std.fmt.parseInt(u8, "999", 10) catch |err| blk: {
std.debug.print("could not parse: {t}\n", .{err});
break :blk 255;
};
std.debug.print("c={d}\n", .{c});
}a=120 b=0
could not parse: Overflow
c=255
try: pass it up
Often a function can't fix an error itself and should just report it to its caller. try expr is shorthand for expr catch |err| return err:
const std = @import("std");
const Rgb = struct { r: u8, g: u8, b: u8 };
// "#ff8800" -> Rgb
fn parseHexColor(text: []const u8) !Rgb {
if (text.len != 7 or text[0] != '#') return error.BadFormat;
return .{
.r = try std.fmt.parseInt(u8, text[1..3], 16),
.g = try std.fmt.parseInt(u8, text[3..5], 16),
.b = try std.fmt.parseInt(u8, text[5..7], 16),
};
}
pub fn main() void {
const samples = [_][]const u8{ "#ff8800", "#12zz56", "blue" };
for (samples) |s| {
const color = parseHexColor(s) catch |err| {
std.debug.print("{s}: {t}\n", .{ s, err });
continue;
};
std.debug.print("{s}: r={d} g={d} b={d}\n", .{ s, color.r, color.g, color.b });
}
}#ff8800: r=255 g=136 b=0
#12zz56: InvalidCharacter
blue: BadFormat
Notice the return type !Rgb with no error set before the !. Zig infers the error set from every return error.X and every try in the body — here BadFormat, plus InvalidCharacter and Overflow from parseInt.
Errors in main
main may return an error union too (pub fn main() !void). That lets you use try directly in main; if an error reaches the top, the program prints error: Name, an error return trace, and exits with a non-zero status. In this course we usually catch errors in main so the output stays tidy.
Merging error sets and switching on errors
Error sets can be combined with ||. Because errors are values, you can switch on them, and the switch must be exhaustive:
const std = @import("std");
const NetworkError = error{ Timeout, Refused };
const FileError = error{ NotFound, NoPermission };
const LoadError = NetworkError || FileError;
fn load(source: u8) LoadError![]const u8 {
return switch (source) {
0 => "data",
1 => error.Timeout,
2 => error.NotFound,
else => error.NoPermission,
};
}
pub fn main() void {
for (0..4) |i| {
const result = load(@intCast(i)) catch |err| switch (err) {
error.Timeout, error.Refused => "retry later",
error.NotFound => "use defaults",
error.NoPermission => "ask an admin",
};
std.debug.print("source {d}: {s}\n", .{ i, result });
}
}source 0: data
source 1: retry later
source 2: use defaults
source 3: ask an admin
Ignoring errors is impossible
You cannot use an error union as if it were the value. Using checkAge(30) + 1 fails with "error union is ignored" or a type mismatch. If you are certain an error cannot happen, write catch unreachable — in safe builds that panics if you were wrong.
Summary
| Syntax | Meaning |
|---|---|
error{ A, B } |
an error set |
E!T / !T |
error union (explicit / inferred set) |
return error.A; |
fail |
try x |
unwrap or return the error to the caller |
x catch v |
unwrap or use v |
x catch |e| { … } |
unwrap or handle the error |
if (x) |v| … else |e| … |
branch on success/failure |
@errorName(e) / {t} |
the error's name as text |
Test yourself
What does try foo() do when foo returns an error?
- Panics
- Returns the error from the current function
- Ignores it
- Retries the call
What does the return type !u32 mean?
- Not a u32
- An optional u32
- A u32 or an error from an inferred error set
- A pointer to u32
What is std.fmt.parseInt(u8, "x", 10) catch 7?
- 7
- 0
- error.InvalidCharacter
- A compile error