errdefer for Failure Cleanup
Undo work only when something fails.
errdefer for Failure Cleanup is a free Zig Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Zig Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Cleanup Only on Failure
Sometimes you must undo work when an operation fails, but keep it when it succeeds. That precise case is what errdefer is for.
Meet errdefer
An errdefer schedules code to run as the scope exits, but only when the function returns an error from that point onward.
errdefer allocator.free(buffer);defer Always, errdefer on Error
A defer runs no matter how the scope ends. An errdefer runs only on the error path, so success skips it entirely.
Free a Half-Built Result
Allocate, then errdefer the free. If a later step fails the buffer is released; if all steps pass you keep and return it.
const buf = try allocator.alloc(u8, n);
errdefer allocator.free(buf);
try fill(buf);Order Mirrors Allocation
Place each errdefer right after the matching acquire. On failure they run in reverse, unwinding resources in a safe order.
const a = try open();
errdefer a.close();
const b = try open();
errdefer b.close();Success Keeps Your Work
When the function returns a value instead of an error, every errdefer is skipped. The caller receives the fully built result.
return buf;Trigger Point Matters
An errdefer only guards errors that happen after it is registered. Errors before that line cannot run it, so place it early.
Capture the Error
You can capture the error in an errdefer to inspect it during cleanup, for example to log which failure triggered the rollback.
errdefer |e| std.debug.print("failed: {}\n", .{e});Builds Leak-Free Constructors
Functions that allocate then might fail use errdefer to stay leak-free. Partial work is undone automatically on any error.
Combine with try
Each try may exit early on error. With an errdefer registered, that early exit still triggers your cleanup before unwinding.
const x = try step();
errdefer rollback(x);
_ = try next(x);The Right Tool for Rollback
Use errdefer when cleanup should happen only if things go wrong. It turns error-path resource management into a single clear line.
Quick Check
You allocate a buffer, then a later step may fail. You want it freed only on failure. What do you use?
Recap
You used errdefer to undo partial work on the error path, placed it right after each acquire, and kept successful results intact. ✅
Frequently asked questions
Is the “errdefer for Failure Cleanup” lesson free?
Yes — the full text of “errdefer for Failure Cleanup” is free to read here on the web, and the Zig Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Zig Academy course, upgrade to CoddyKit PRO.
What will I learn in “errdefer for Failure Cleanup”?
Undo work only when something fails. You practise Zig Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Zig Academy?
No prior experience is required. Zig Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “errdefer for Failure Cleanup” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Zig Academy lesson?
Yes. Every Zig Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Recover with catch
- Switch on Specific Errors
- errdefer for Failure Cleanup
- Wrapping and Re-throwing Errors