Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Allocators and Error Handling

Error Unions and try

Understand Zig errors as values: error sets, error union types like !T, try, catch, if/else capture, switching on errors and error return traces, with Go stand-ins.

Zig has no exceptions. A function that can fail says so in its return type, and the compiler forces every caller to deal with that. Errors are ordinary values, they cost no hidden control flow, and you can see every possible failure path by reading the code.

Error sets and error unions

An error set is a set of named error values. You create one with the error keyword:

ZIG
const FileError = error{
    NotFound,
    PermissionDenied,
};

An error union combines an error set with a normal type, written ErrorSet!T. A value of type FileError!u32 is either a u32 or one of the two errors. Most of the time you write just !T and let the compiler infer the exact set of errors from the function body:

ZIG
const std = @import("std");

fn parsePort(text: []const u8) !u16 {
    return std.fmt.parseInt(u16, text, 10);
}

Here parseInt can return error.InvalidCharacter or error.Overflow, so parsePort carries those errors too. An error is created with error.Name, as in return error.NotFound;.

try: pass the error up

try x means "if x is an error, return it from this function immediately; otherwise unwrap the value". It is shorthand for x catch |err| return err.

ZIG
fn loadConfig(text: []const u8) !u16 {
    const port = try parsePort(text); // returns the error to our caller
    if (port < 1024) return error.PrivilegedPort;
    return port;
}

try is one word you will write hundreds of times. It is deliberate: every place that can fail is visibly marked.

catch: handle it here

catch gives a fallback value, or runs code with the error captured:

ZIG
const a = parsePort("8080") catch 80;            // default value
const b = parsePort("oops") catch |err| blk: {
    std.debug.print("bad port: {s}\n", .{@errorName(err)});
    break :blk 80;
};

@errorName turns an error into its text. If an error truly "cannot happen", write catch unreachable (or catch @panic("...")). In safe build modes that traps if you were wrong; in release-fast it is undefined behavior, so use it sparingly.

if and else

You can unwrap with if, capturing the payload in the success branch and the error in the else branch:

ZIG
if (parsePort("443")) |port| {
    std.debug.print("port {d}\n", .{port});
} else |err| {
    std.debug.print("error {s}\n", .{@errorName(err)});
}

switch on errors

A switch over an error value must handle every possible error, or have an else:

ZIG
const msg = switch (err) {
    error.InvalidCharacter => "not a number",
    error.Overflow => "too big",
    else => "other",
};

If you list all errors without an else, adding a new error to the callee later makes this switch fail to compile, which is exactly the reminder you want.

Main can return an error

pub fn main() !void is allowed. If it returns an error the program prints error: <Name> plus an error return trace and exits with a non-zero code.

ZIG
pub fn main() !void {
    const port = try loadConfig("22");
    std.debug.print("{d}\n", .{port});
}

The error return trace is not a normal stack trace: it records the places where the error was returned (every try it passed through) from where it was created up to main. It is a big help when an error surfaces far from its origin. It is available in debug builds.

Errors vs optionals

Zig has two ways to say "no result". Pick by meaning:

Use Type Example
Absence is normal and needs no reason ?T map.get(key), list.pop()
Failure with a reason you may report or switch on E!T parsing, opening files, allocating

You can combine them: !?T means "may fail, and on success may have nothing". Unwrapping an optional uses orelse: const v = map.get(k) orelse return error.Missing;.

Merging error sets

|| merges two sets: const AppError = FileError || std.mem.Allocator.Error;. With inferred !T you rarely need it. Prefer inferred sets for internal functions and explicit sets for public APIs, where the error list is part of the contract.

flowchart LR
  A["parseInt<br/>InvalidCharacter | Overflow"] -->|try| B["parsePort<br/>same errors"]
  B -->|try| C["loadConfig<br/>+ PrivilegedPort"]
  C -->|try| D["main<br/>prints error + trace"]

Caption: with try, errors flow up the call chain and the inferred sets grow on the way.

Runnable stand-ins

Go also treats errors as values, so it makes a fair stand-in. Go's if err != nil { return err } is the manual form of Zig's try, and errors.Is plays the role of switch on an error.

Go Stand-in: errors as values, try-like propagation (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A second stand-in shows the "default value" form (catch 80) and the optional/error distinction:

Go Stand-in: defaults and optional vs error (Go)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Common mistakes

  • Using catch unreachable to silence the compiler on errors that can really happen.
  • Ignoring an error union: Zig refuses to compile unused error unions, which is a feature.
  • Returning ?T when callers would benefit from knowing why it failed.
  • Writing huge explicit error sets by hand instead of letting inference do it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does try x do when x is an error?

    try x is shorthand for x catch |err| return err, so the error propagates to the caller.
  2. 2. What does the type !u16 mean?

    !T is an error union whose error set is inferred from the function body.
  3. 3. When should you use ?T instead of !T?

    Optionals say 'nothing here' without a reason; error unions say 'it failed, and here is why'.
  4. 4. What is an error return trace?

    It records where the error was returned, which points to the origin even if the error surfaces far away.

Summary

  • Zig errors are values; there are no exceptions.
  • E!T (or !T) is an error union; try propagates, catch handles, if ... else |err| unwraps.
  • A switch on an error must cover every case, so changes to a callee are caught at compile time.
  • Use ?T for normal absence and !T for failures with reasons.

Next: errdefer and error sets