by Zambyte · 1y ago · 0 comments
One interesting difference between Zig and other languages with similar error stories (Rust, Go) is that panicking can be handled but not recovered. Panicking is always fatal in Zig. The nice thing about this is that you cannot use panics for exception-style control flow, which removes any temptation to use them for user errors.
[0] https://ziggit.dev/t/i-wrote-a-simple-sudoku-solver/9924/12?...
Not that the language itself make it hard, on the contrary, but the standard library itself is littered with opinionated error handling that straight up panic with no recovery at every corner.
For instance, it was decided that the kernel returning EINVAL for any syscall is worth panicking, even though there are a lot of cases where that is recoverable. The answer from Andrew? It's the kernel's fault. Very helpful.
Quotes are cute, but their actual implementation matters more.
> It should be handled on a case-by-case basis. For some syscalls, EINVAL should be unreachable because it can only mean something like an invalid pointer address being passed to the kernel, or invalid flags.
> However, as you pointed out, some kernel APIs unfortunately have decided to dual-purpose this error code to mean other things, in which case we must to handle the ambiguity by mapping it to an error code. We had to make this change with EBADF recently for some syscalls, for example.
> I do want to keep the error sets clean, however, so I am opposed to a blanket modification of all EINVAL code sites without cause.
Source: https://github.com/ziglang/zig/issues/6925#issuecomment-7214...
https://github.com/ziglang/zig/issues/6389#issuecomment-2895...
It doesn't look to be too much of a temptation to use panics as regular errors in Rust though, so I don't think it gains you much.
And it makes it more complicated when you want to catch panics for legitimate reasons (like when you want to show an error box to the user, instead of silently crashing, or when you want to send the crash log for later analysis). It's still possible, by using a separate process, but it's unnecessary friction in order to prevent a sin that doesn't happen in practice.
Maybe not, but it was enough for the author to dedicate at least one whole section of the article to reasoning about this.
> like when you want to show an error box to the user, instead of silently crashing, or when you want to send the crash log for later analysis
As I mentioned, panics can be handled but not recovered. You can use the panic handler to do these things just fine. Just not recover.
What does this difference mean? If you can run arbitrary function in your panic handler, what prevents someone from continuing the program?
That's been the general mantra for at least a decade or two. And I think it's right.
What does it mean to "handle" but not "recover" a panic?