Hello guys, I’m relatively new to Zig, and I was wondering why this issue has been closed.
Isn’t something like this essential for a programming language?(At least it makes things easier)
Is there a technical issue with the implementation?
I think this is another case where Zig is deliberately guiding you away from the “easy” solution, towards a more readable and more robust solution.
Error values make it easy to just throw all the errors and catch them in the main function, print some stuff and then crash. I did this back when I was still using java, and it was crashing all the time.
The better solution is to handle errors locally, when you still have the information what caused the errors. I find that handling errors locally helps me finding a graceful way of dealing with it. And if you handle errors locally you will find that you rarely need error values, and if you do you can just store it somewhere locally.
Furthermore I think error values would make resource management more difficult, like what if your error value contains a heap allocated string? This can cause soo many problems.
@IntegratedQuantum spelled out the thinking behind this decision pretty clearly. However, in the event that you do need the extra diagnostic information, the stdlib favors the Diagnostics
approach. You can search the stdlib docs for “Diagnostics” to see some examples, such as std.json.Diagnostics
.
This approach is most commonly useful for parser errors from what I’ve seen. Initially, it doesn’t feel the most ergonomic, but it’s a very useful pattern once you get used to it.
(To clarify, this isn’t me advocating for or against the current status quo. Just offering a possible solution.)
The colloquial meaning of an error is perhaps not well aligned with zig’s error unions. Zig’s error unions could be used to mean “bad thing happened” but it doesn’t fit all use cases. The current design of errors is closer to “a refusal to return a value”. Its like returning null
but you have the ability to switch on the errors for control flow.
In the issue, Andrew says “error codes are for control flow”. One could also interpret this as “error codes are not informative”, or “error codes are not values”.
If you are tempted to return a value with an error, consider if you should instead return a union. Being tempted to return a value could be an indication that you are attempting to hide or categorize information that should be part of the normal control flow of the program.
At least this is how I interpret how API’s should be designed under “error codes are for control flow”.