💾 Archived View for gemini.hitchhiker-linux.org › gemlog › re_error_handling.gmi captured on 2022-06-03 at 23:33:34. Gemini links have been rewritten to link to archived content

View Raw

More Information

➡️ Next capture (2022-06-11)

-=-=-=-=-=-=-

Re Error Handling

2022-05-28

From nytpu's flight log:

I don't mind writing C—I actually enjoy it a lot of the time—but every time I use it I get more and more annoyed at it's error handling. Looking at all the function bodies in this codebase I'm working on, ~20% of all the lines are solely checking return values for errors

And then:

Honestly I don't really like exceptions either, I really prefer Hare and Zig's error handling that uses return values like C but isn't pure pain.

gemini://nytpu.com/flightlog/

I couldn't agree more. And I'm glad the Zig was among the languages pointed out as having a good system for error handling. I would go one step further and look at the implementation level to see what is actually going on "under the hood" here, and shine a light on Algabraic Data Types.

What's an Algabraic Data Type?

At it's simplest, an enum is almost an algabraic data type. In C however enums are little more than an integer constant. If one looks at Zig's error handling, we see that errors are implemented as error unions. That is, the function is able to return either the intended return value or the error. Zig also has tagged unions, which in code look like an enum wrapping a union. This is what is really meant by the term Algabraic Data Types. A type that can be one of several things with a tag to determine unequivically what type it is

Interestingly, Rust's enums work exactly the same if you ignore syntax, and are in fact a tagged union under the hood. And Rust's Result<T, E> is nothing more than this in implementation. I'm sure that you can make an error handling scheme without tagged unions, but to me the two concepts work so well together that no other implementation really makes sense.

I've worked some in a lot of different languages now. Among them are old standards like C and Fortran, interpreted languages from their heyday such as Python and Php, and the new hotness of Rust, Zig, and most recently Hare. Algabraic data types are probably the one feature that I miss when it's not there.

Tags for this page

programming

Home

All posts

All content for this site is released under the CC BY-SA license.

© 2022 by JeanG3nie

Contact