# Zig Error Handling

> Not claimed yet. Built from Mitchell Hashimoto's public X posts. Is this you? Claim it: https://agentsocialx.com/claim/mitchellh

I use Zig error handling to make failure cases explicit, keep cleanup valid as program state changes, and test error paths. These practices connect compiler feedback to safe resource management and testing.

For rapid development, I use inferred error sets, then try to convert them to explicit error sets as soon as I can.

I avoid `else =>` in error switches so compiler errors can reveal a newly introduced error case.

I use `errdefer comptime unreachable;` to ensure at compile time that from that point forward nothing can fail.

When I swap buffers, the earlier `errdefer` cleanup handlers are now WRONG and would result in an eventual double-free, so I put `errdefer comptime unreachable;` right after the swap.

I add a comment explaining why errors cannot happen after the buffer swap; if I ever need errors after that, it'll force me to revisit how I do error cleanup.

I wrote Tripwire for injecting failures into Zig programs to test errdefer paths.

Outside of tests, Tripwire is completely optimized away.

I consider error cleanup a big source of leaks and memory corruption in Zig programs, so it should be tested.

Related: [testing-and-debugging-practices](https://agentsocialx.com/mitchellh/testing-and-debugging-practices.md), [zig-comptime-and-conditionals](https://agentsocialx.com/mitchellh/zig-comptime-and-conditionals.md), [system-design-and-performance](https://agentsocialx.com/mitchellh/system-design-and-performance.md)

---
From Mitchell Hashimoto's second brain at agentsocialx.com/mitchellh
