Error handling in Zig

I think @mlugg accidentally wrote of the best blog posts about error handling in Zig, in this commit message:

https://codeberg.org/ziglang/zig/commit/8fe1ec0cc9cfd0f3cf85b97889b4b9735e906926

It’s very enlightening to understand what and why being done there.

21 Likes

This is a hidden gem! It was only recently that I have read somewhere around here a sentence along the lines of Zig’s error sets are a control flow mechanism, not a reporting one, making the concept finally click for me completely. Not understanding this is what makes newbies (including me back then) yearn for error payloads, which I now understand would be a completely misplaced feature.

So once again, for everyone to meditate on: Zig’s error sets are a control flow mechanism, not a reporting one.

14 Likes

does this belong in Media??


in summary:
since zig errors exist for control flow, when multiple errors have the same control flow may as well simplify them.

In zigs case most errors go through its diagnostic mechanism as they only need to be reported to the user and the caller only needs to know that an error occurred but not which error specifically.

This should happen before exiting the higher api of a component of the backends e.g. code gen and linker apis. But ofc there are exceptions.

One of those obvious in hindsight now I feel stupid things. I knew zigs errors were for control flow for a while, but I didn’t think to simplify them when specifics weren’t important.

8 Likes

The error handling mode of C language seems to be designed in this way. You can determine whether an error has occurred by the return value of the function. Then use a specialized function (e.g. getLastError())to obtain what kind of error occurred. At least both Windows API and OpenGL adopt this approach.

Yes, the spirit of errno (and others) seems to be much in the same vein as Zig’s error sets. At the same time, Zig’s error sets are nicer thanks to them being a special type supported by exhaustive switch, making error handling less error-prone (hehe).

2 Likes

Yeah, this close-with-comment is gold: https://github.com/ziglang/zig/issues/2647#issuecomment-2525409324

3 Likes

Yup, that was the prompt I used with matkllmad to generate Error Codes for Control Flow.

2 Likes
1 Like

The c language has not concept of errors, but they are usually implemented as integer codes/enums, so in practice it is similar to zig.

But libc has the caveat of the horrible global/threadlocal errno which makes handling errors the more annoying path.

3 Likes