Hacker News new | past | comments | ask | show | jobs | submit login

I think it's nice to have two mechanisms for errors like in ML: sum types for errors that the calling function can realistically recover from, and exceptions for the rest.



You can do that in zig with @panic and even convert from sum type error to an irrecoverable exception: `catch @panic("oops");`


That's nice. Are the sum types checked by the compiler to ensure that you didn't miss any case?


Yes, and you can even handle some errors, and then capture an error whose type is the subset of unhandled errors, and return that, limiting the error set of the current function to not include the handled ones. Here are a couple examples: https://github.com/ziglang/zig/blob/7d0de54ad44832589379a4bc...

You get compile errors if you try to handle an impossible error, or don't include an `else` prong (in which case the compiler tells you the full set of unhandled errors).


That's a great feature. I'm constantly impressed by what Zig can do.


If I understand you correctly, then yes.

    fn canError(foo: bool) !void {
        if (foo) {
            return error.Foo;
        } else {
            return error.Bar;
        }
    }

    test "canError" {
        canError(true) catch |e| switch (e) {
            error.Foo => @panic("foo!"),
        };
    }
Running `zig test` on that file would give:

    ./tmp/errors.zig:10:30: error: error.Bar not handled in switch
        canError(true) catch |e| switch (e) {
                                 ^


You did understand it correctly. That's a really nice feature.


This is Rust's approach, too: realistically recoverable errors are handled with Result<T, E>, and other are handled through panics. (Panics are generally implemented as exceptions, i.e. they unwind the stack, but the compiler can also be configured to make them just abort.)


C has always had Asserts for that reason.


Is it idiomatic to assert things and recover from them the way people sometimes do with exceptions?




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: