Zig Errors
Programs meet problems all the time: a file isn’t there, a user types “abc” where you wanted a number, the network drops. Zig doesn’t use exceptions for this. A function that can fail returns the error, just like it returns a normal value, and the compiler won’t let the caller forget about it. This lesson shows what an error is in Zig, how to write a function that can fail, and the first easy ways to deal with the result.
An error is just a name
Section titled “An error is just a name”In Zig, an error is a simple named value, written error. followed by a name you choose:
const std = @import("std");
pub fn main() void { const problem = error.NotFound; std.debug.print("something went wrong: {t}\n", .{problem}); std.debug.print("same thing: {s}\n", .{@errorName(problem)});}Output:
something went wrong: NotFoundsame thing: NotFounderror.NotFound carries no message, no line number and no extra data. It’s just a name, a bit like a value of an enum. You don’t declare it anywhere first: writing error.NotFound is enough, and Zig gives every distinct error name in your program its own small number behind the scenes.
To print an error, use {t} in the format string (the “t” stands for tag name), or turn it into a string with @errorName(err). Both give you the name without the error. part.
Error sets: the list of things that can go wrong
Section titled “Error sets: the list of things that can go wrong”Usually you group the errors a piece of code can produce into an error set. It looks like an enum, with error in front:
const std = @import("std");
const LoginError = error{ WrongPassword, AccountLocked, UnknownUser,};
pub fn main() void { const err: LoginError = error.AccountLocked; std.debug.print("login failed: {t}\n", .{err}); std.debug.print("is it locked? {}\n", .{err == error.AccountLocked});}Output:
login failed: AccountLockedis it locked? trueLoginError is a type. A value of that type can only be one of the three errors listed. You can compare errors with ==, which is how you’d check for one specific problem.
Error names are global: error.NotFound in one error set is the very same value as error.NotFound in another. That’s on purpose, and it’s what lets errors flow from one set into a bigger one later.
Error unions: a value or an error
Section titled “Error unions: a value or an error”A function that can fail returns an error union: either a normal value or an error. You write it as ErrorSet!ValueType, read as “this error set, or this value”:
const std = @import("std");
const LookupError = error{ NotFound, Empty };
fn findAge(name: []const u8) LookupError!u8 { if (name.len == 0) return error.Empty; if (std.mem.eql(u8, name, "Ada")) return 36; if (std.mem.eql(u8, name, "Linus")) return 56; return error.NotFound;}
pub fn main() void { const names = [_][]const u8{ "Ada", "Bob", "" }; for (names) |name| { const result = findAge(name); std.debug.print("'{s}': {!d}\n", .{ name, result }); }}Output:
'Ada': 36'Bob': error.NotFound'': error.EmptyLookupError!u8 means “an age, or one of the errors in LookupError”. Inside the function you just return whichever you have: return 36 and return error.NotFound are both fine, and Zig wraps them up for you.
The {!d} in the format string prints an error union: the number if there is one, the error if not. That’s handy for a quick look, but real code wants to do something with each case, and that’s what the next sections are about.
You can’t use the value directly
Section titled “You can’t use the value directly”An error union isn’t a u8. It might be an error, so Zig won’t let you treat it as a number:
const std = @import("std");
fn findAge(name: []const u8) !u8 { if (std.mem.eql(u8, name, "Ada")) return 36; return error.NotFound;}
pub fn main() void { const age = findAge("Ada"); std.debug.print("next year: {d}\n", .{age + 1});}main.zig:10:47: error: invalid operands to binary expression: 'error_union' and 'comptime_int' std.debug.print("next year: {d}\n", .{age + 1}); ~~~~^~~You first have to unwrap it: say what happens if it’s an error, and get the plain u8 out if it isn’t. (The !u8 without a set name in front is explained a bit further down.)
Unwrapping: catch and if
Section titled “Unwrapping: catch and if”Here are the two simplest ways to unwrap an error union. The next lesson, Zig Try & Catch, goes much further.
catch with a default value. “Give me the value, or this fallback if it failed”:
const std = @import("std");
fn findAge(name: []const u8) !u8 { if (std.mem.eql(u8, name, "Ada")) return 36; return error.NotFound;}
pub fn main() void { const ada = findAge("Ada") catch 0; const bob = findAge("Bob") catch 0; std.debug.print("Ada: {d}, Bob: {d}\n", .{ ada, bob });}Output:
Ada: 36, Bob: 0After catch 0, ada and bob are plain u8 values. The error is gone because you decided what it means.
if with two captures. When you want different code for success and failure, use if on the error union. The value goes into |age|, the error into else |err|:
const std = @import("std");
fn findAge(name: []const u8) !u8 { if (std.mem.eql(u8, name, "Ada")) return 36; return error.NotFound;}
pub fn main() void { const names = [_][]const u8{ "Ada", "Bob" }; for (names) |name| { if (findAge(name)) |age| { std.debug.print("{s} is {d}\n", .{ name, age }); } else |err| { std.debug.print("no age for {s}: {t}\n", .{ name, err }); } }}Output:
Ada is 36no age for Bob: NotFoundThis looks like the if with captures you’ll meet for optionals, with one extra part: the else |err|. With an error union, the else part is required, because the error has to go somewhere.
Inferred error sets: !T
Section titled “Inferred error sets: !T”Writing out every error set by hand gets tiring for small functions. If you leave the set out and write just !u8, Zig looks at every return error.X in the function (and every error it passes on from functions it calls) and builds the set for you:
const std = @import("std");
fn half(n: u32) !u32 { if (n % 2 != 0) return error.OddNumber; return n / 2;}
pub fn main() void { std.debug.print("{!d}\n", .{half(10)}); std.debug.print("{!d}\n", .{half(7)}); std.debug.print("{s}\n", .{@typeName(@TypeOf(half(10)))});}Output:
5error.OddNumber@typeInfo(@typeInfo(@TypeOf(main.half)).@"fn".return_type.?).error_union.error_set!u32The last line is Zig’s way of saying “the error set that was inferred for half, or a u32”. It’s not pretty, and you’ll see that long name in compiler errors too, so it’s good to recognize it.
Most everyday Zig code uses !T. An explicit set like LookupError!u8 is better for public functions that other code calls, because it documents exactly what can go wrong and the compiler checks it. For example, a typo in an error name is caught right away:
const LookupError = error{NotFound};
fn find(n: u32) LookupError!u32 { if (n == 0) return error.NotFond; return n * 2;}
pub fn main() void { _ = find(3) catch 0;}main.zig:4:30: error: expected type 'error{NotFound}!u32', found 'error{NotFond}' if (n == 0) return error.NotFond; ^~~~~~~main.zig:4:30: note: 'error.NotFond' not a member of destination error setWith !u32 instead, that typo would quietly become a brand new error called NotFond. Zig Custom Error Sets talks more about when to pick which.
You can’t ignore an error
Section titled “You can’t ignore an error”This is the rule that makes Zig’s errors work: if a function can fail, you must handle the result. Calling it and walking away doesn’t compile:
const std = @import("std");
fn save(n: u32) !void { if (n > 100) return error.TooBig; std.debug.print("saved {d}\n", .{n});}
pub fn main() void { save(5);}main.zig:9:9: error: error union of type '@typeInfo(@typeInfo(@TypeOf(main.save)).@"fn".return_type.?).error_union.error_set!void' is ignored save(5); ~~~~^~~main.zig:9:9: note: consider using 'try', 'catch', or 'if'Even _ = save(5);, which throws away other values, is refused with “error union is discarded”. If you really do want to ignore a failure, you have to say so with save(5) catch {};. That way, every ignored error is visible in the code, and a reviewer can ask “are we sure?”.
anyerror: every error there is
Section titled “anyerror: every error there is”anyerror is the error set that contains every error in your whole program. Any error can be stored in it:
const std = @import("std");
pub fn main() void { var last: anyerror = error.Timeout; std.debug.print("last error: {t}\n", .{last}); last = error.DiskFull; std.debug.print("last error: {t}\n", .{last});}Output:
last error: Timeoutlast error: DiskFullIt sounds convenient, but you lose information: with anyerror, nobody can tell which errors a function can really return, and the compiler can’t check that you’ve handled all of them. Use it only where you truly need “any error at all”, like a field that stores the last failure of anything. For functions, prefer !T or a named set.
When main returns an error
Section titled “When main returns an error”main can fail too. Give it the return type !void, and if an error comes out of it, Zig prints the error name and exits with code 1. The try here means “if this failed, return the error from main right away”; it gets its full explanation in Zig Try & Catch:
const std = @import("std");
fn findUser(id: u32) error{NotFound}![]const u8 { if (id == 1) return "Ada"; return error.NotFound;}
pub fn main() !void { const name = try findUser(1); std.debug.print("found {s}\n", .{name});
const other = try findUser(7); std.debug.print("found {s}\n", .{other});}You’ll see something like:
found Adaerror: NotFoundmain.zig:5:5: 0x11e5f62 in findUser (main.zig) return error.NotFound; ^main.zig:12:19: 0x11e4206 in main (main.zig) const other = try findUser(7); ^Below error: NotFound is an error return trace: the path the error took, from where it was created (line 5) to where it left main (line 12). The 0x... addresses change between builds, so don’t worry about them. This trace is printed in debug builds only; Zig Error Return Traces shows how to read it and how to get it in other build modes.
The error set here is written inline as error{NotFound}, without a name. That’s allowed anywhere a type goes.
What errors can’t do
Section titled “What errors can’t do”Be aware of one limit early: an error can’t carry extra data. error.NotFound can’t hold the name that wasn’t found, and error.BadNumber can’t hold the line it was on. That’s a deliberate choice: errors stay small and cheap to pass around, and they never need memory. When you need details, the usual answer is a small “diagnostics” struct that the caller passes in, which Zig Custom Error Sets shows step by step.
The language reference on errors covers everything in this lesson, with the official examples.
Practice
Section titled “Practice”1. Check a password
Section titled “1. Check a password”Write fn checkPassword(pw: []const u8) !void that returns error.TooShort when the password has fewer than 8 characters and error.NoDigit when it has no digit 0 to 9. In main, test "hi", "longpassword" and "secret123" with if ... else |err|, and print either ok or the error name.
Hint: std.ascii.isDigit(c) checks one character. Loop over the bytes with for (pw) |c|.
Show solution
const std = @import("std");
fn checkPassword(pw: []const u8) !void { if (pw.len < 8) return error.TooShort; for (pw) |c| { if (std.ascii.isDigit(c)) return; } return error.NoDigit;}
pub fn main() void { const tries = [_][]const u8{ "hi", "longpassword", "secret123" }; for (tries) |pw| { if (checkPassword(pw)) { std.debug.print("{s}: ok\n", .{pw}); } else |err| { std.debug.print("{s}: {t}\n", .{ pw, err }); } }}Output:
hi: TooShortlongpassword: NoDigitsecret123: okThe function returns !void, so there’s no value on success. That’s why the if has no |value| capture, only the else |err|. A bare return; in a !void function means “success”.
2. Name the error set
Section titled “2. Name the error set”Rewrite the solution above so that checkPassword returns an explicit error set called PasswordError. Then add a third check: return error.HasSpace if the password contains a space, and see what the compiler says if you forget to add HasSpace to the set.
Hint: the set is const PasswordError = error{ ... };, and the return type becomes PasswordError!void.
Show solution
const std = @import("std");
const PasswordError = error{ TooShort, NoDigit, HasSpace };
fn checkPassword(pw: []const u8) PasswordError!void { if (pw.len < 8) return error.TooShort; if (std.mem.findScalar(u8, pw, ' ') != null) return error.HasSpace; for (pw) |c| { if (std.ascii.isDigit(c)) return; } return error.NoDigit;}
pub fn main() void { const tries = [_][]const u8{ "hi", "my secret 1", "secret123" }; for (tries) |pw| { if (checkPassword(pw)) { std.debug.print("{s}: ok\n", .{pw}); } else |err| { std.debug.print("{s}: {t}\n", .{ pw, err }); } }}Output:
hi: TooShortmy secret 1: HasSpacesecret123: okLeave HasSpace out of the set and you get “‘error.HasSpace’ not a member of destination error set”. The set is now a promise the compiler holds you to. std.mem.findScalar returns the position of the space, or null if there isn’t one (more on null in Zig Optionals).
- An error is a named value like
error.NotFound. Print it with{t}or@errorName. - An error set lists the errors something can return:
error{ NotFound, Empty }. - An error union
E!Tis either a value of typeTor an error fromE.!Tlets Zig infer the set. - You must unwrap an error union before using the value:
catchwith a default, orif (x) |v| ... else |err| .... - Ignoring an error is a compile error. Ignore one on purpose with
catch {}. anyerrorholds every error, but you lose the compiler’s checks. Prefer!Tor named sets.- When
mainreturns an error, Zig prints its name and an error return trace and exits with code 1.
Next up: Zig Try & Catch, the everyday tools for passing errors on or handling them on the spot.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Errors: error sets, error unions,
catch,tryand more, with examples. - Zig language reference: The global error set: what
anyerroris and when to use it. - Zig in-depth overview: the “A fresh take on error handling” part explains why Zig works this way.
- Ziglings: small exercises; several early ones are about errors.