Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Allocators and Error Handling

errdefer and Custom Error Sets

Clean up safely when things fail in Zig: defer versus errdefer, error captures, designing custom error sets, merging sets, anyerror and diagnostics, with a Go stand-in.

Writing code that handles failure is mostly about cleanup: if the third step of a five-step setup fails, the first two must be undone. In C you chain goto cleanup labels. In Zig you use defer and errdefer, and the compiler makes sure each runs at the right time, in the right order.

defer versus errdefer

  • defer expr; runs expr when the current scope exits for any reason (normal end, return, break, error).
  • errdefer expr; runs expr only when the scope exits by returning an error.

Both run in reverse order (last declared, first run), like a stack.

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

const Connection = struct {
    name: []const u8,

    fn open(gpa: std.mem.Allocator, name: []const u8) !*Connection {
        const self = try gpa.create(Connection);
        self.* = .{ .name = name };
        return self;
    }

    fn close(self: *Connection, gpa: std.mem.Allocator) void {
        gpa.destroy(self);
    }
};

fn setup(gpa: std.mem.Allocator) !struct { a: *Connection, b: *Connection } {
    const a = try Connection.open(gpa, "primary");
    errdefer a.close(gpa); // only if something later fails

    const b = try Connection.open(gpa, "replica");
    errdefer b.close(gpa);

    try handshake(a, b); // may fail: both errdefers run, b then a
    return .{ .a = a, .b = b }; // success: nothing is closed here
}

The pattern is: acquire a resource, and on the very next line write the errdefer that releases it. After return, ownership belongs to the caller, who writes a normal defer for each.

flowchart TD
  A["open a"] --> B["errdefer close a"]
  B --> C["open b"]
  C --> D["errdefer close b"]
  D --> E{"handshake ok?"}
  E -->|yes| F["return both<br/>(no cleanup)"]
  E -->|no| G["run errdefers:<br/>close b, then close a"]

Caption: errdefers form a stack that only unwinds on the failure path.

Capturing the error

errdefer |err| ... gives you the error value, handy for logging:

ZIG
errdefer |err| std.debug.print("setup failed: {s}\n", .{@errorName(err)});

defer and loops

A defer inside a loop body runs at the end of each iteration, not at the end of the function. That is usually what you want for per-item resources:

ZIG
for (paths) |path| {
    const buf = try gpa.alloc(u8, 4096);
    defer gpa.free(buf); // freed every iteration
    try process(path, buf);
}

Things defer cannot do

  • You cannot return or try inside a defer block (the cleanup itself must not fail). If cleanup can fail, handle the error inside: file.close() generally does not return an error for that reason.
  • Deferred expressions are evaluated when the scope exits, not when declared, so they see the latest values of variables.

Designing error sets

An error set is part of a function's public face. Some guidelines:

  1. Small and meaningful names. error.NotFound, error.Timeout, error.InvalidSyntax. Names are global strings: error.NotFound in one library is the same value as error.NotFound in another.
  2. Explicit sets for public APIs. Write fn read(...) ReadError!usize so documentation and callers see exactly what can happen.
  3. Inferred sets for private helpers. Let the compiler track them.
  4. No catch-all in libraries. Avoid returning anyerror unless you really cannot know the set (callbacks, generic code). It loses exhaustive switch checking.
ZIG
pub const ParseError = error{
    UnexpectedToken,
    UnterminatedString,
    NumberTooLarge,
};

pub const LoadError = ParseError || std.fs.File.OpenError || std.mem.Allocator.Error;

A || B merges sets. Merged sets are how a high-level function lists everything below it. A caller can narrow with catch:

ZIG
const cfg = loadConfig(gpa, path) catch |err| switch (err) {
    error.FileNotFound => return defaultConfig(),
    else => return err,
};

Here else => return err passes on everything you did not handle, and the compiler still knows the remaining set.

Errors cannot carry data

An error value is just a tag, an integer in disguise. It cannot hold a message or a line number. When you need more detail, return it through a diagnostics out-parameter:

ZIG
pub const Diagnostics = struct {
    line: usize = 0,
    column: usize = 0,
    message: []const u8 = "",
};

pub fn parse(text: []const u8, diag: ?*Diagnostics) ParseError!Ast {
    // on failure:
    if (diag) |d| d.* = .{ .line = 3, .column = 14, .message = "expected ')'" };
    return error.UnexpectedToken;
}

The standard library uses this style for JSON, the Zig parser and others. It keeps the common success path free of extra cost and the error type small.

Panics, unreachable and assertions

Not everything is an error. A bug (an index out of range, a broken invariant) is not something a caller can recover from, so Zig uses @panic("message"), unreachable, std.debug.assert(cond) and safety checks (integer overflow, bounds) that stop the program with a message in Debug and ReleaseSafe builds. Rule of thumb: bad input returns an error; a bad program panics.

A runnable stand-in

Go's defer always runs, and there is no errdefer, but you can model it with a named result and a committed flag. This shows the same stack-like unwinding.

Go Stand-in: errdefer behaviour with Go defer

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.

Look at the failure run: the replica is closed first, then the primary, exactly the order Zig's errdefer would use.

Common mistakes

  • Writing defer gpa.free(buf) and then returning buf: use errdefer.
  • Putting errdefer after a try that can fail: the resource leaks on that failure. Place it immediately after acquiring the resource.
  • Returning anyerror from a library "to be flexible".
  • Trying to attach strings to errors instead of using a diagnostics struct.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does an errdefer statement run?

    errdefer is for cleanup that must happen only on the failure path, keeping the success path's ownership intact.
  2. 2. In what order do multiple defer and errdefer statements run?

    They behave like a stack: the last one declared runs first.
  3. 3. What does A || B do for error sets?

    || merges error sets, which is how a high-level function lists all the errors of the pieces it uses.
  4. 4. How should you report a line number together with a parse error?

    Errors are plain tags and carry no payload. A diagnostics struct passed by pointer carries the extra detail.

Summary

  • defer runs on every exit; errdefer only on error exits; both unwind in reverse order.
  • Place errdefer immediately after acquiring a resource.
  • Design small, meaningful error sets; make public ones explicit and merge with ||.
  • Use diagnostics structs for rich error data and panics for bugs.

Next: Comptime basics