Back to course

Error Propagation and errdefer

Full Course: Zig Programming From Zero to Hero

errdefer

errdefer is like defer, but it only executes if the function returns an error. This is vital for cleaning up partial work during a failed operation.

zig fn createData() !*Data { const data = try allocator.create(Data); errdefer allocator.destroy(data); // Clean up only on error!

try data.initialize();
return data;

}

If initialize() fails, the memory is freed. If it succeeds, the memory is kept.