0PricingLogin
Zig Academy · Lesson

defer vs errdefer in Practice

Choose always-run versus on-error.

Two Cleanup Keywords

Zig gives you two scheduling tools: defer always runs, while errdefer runs only when the scope exits with an error.

defer Means Always

Use defer when cleanup must happen no matter what, like closing a file you opened for the whole function.

const f = try open();
defer f.close();

All lessons in this course

  1. What defer Guarantees
  2. Execution Order of Multiple defers
  3. defer vs errdefer in Practice
  4. Pairing Open with Close
← Back to Zig Academy