0PricingLogin
Zig Academy · Lesson

Switch on Specific Errors

Branch by which error was returned.

Not All Errors Are Equal

One fallback rarely fits every failure. A missing file and bad input often need different handling, so you want to branch by which error occurred.

Capture Then switch

Capture the error from catch, then feed it into a switch. Each case can respond to one specific error in its own way.

open(path) catch |err| switch (err) {
    error.NotFound => create(path),
    else => return err,
};

All lessons in this course

  1. Recover with catch
  2. Switch on Specific Errors
  3. errdefer for Failure Cleanup
  4. Wrapping and Re-throwing Errors
← Back to Zig Academy