How to use errdefer

I thought it would print “errdefer” but it didn’t
am I misunderstanding how errdefer works?

const std = @import("std");
fn compareRandom(rng: std.rand.Random, comp: i64) !i64 {
    const Error = error{TestError};
    var randomNum = rng.intRangeAtMost(i64, 1, 2);
    if (randomNum < comp) {
        return randomNum;
    } else {
        return Error.TestError;
    }
}
fn returnError(rng: std.rand.Random) !i64 {
    var num = try compareRandom(rng, 0);
    errdefer std.log.info("errdefer", .{});
    return num;
}
pub fn main() !void {
    const rngSeed = @intCast(u64, std.time.timestamp());
    const rng = std.rand.DefaultPrng.init(rngSeed).random();
    _ = returnError(rng) catch |err| {
        std.log.info("{s}", .{err});
    };
}
❯ zig build run
info: error.TestError

I thought it would print “errdefer” but it didn’t
am I misunderstanding how errdefer works?

var num = try compareRandom(rng, 0);
errdefer std.log.info("errdefer", .{});

You need to errdefer before possible error return.

2 Likes