19 ms·
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 fo
by Zababa 5y ago
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.
- dnautics 5y agoYou can do that in zig with @panic and even convert from sum type error to an irrecoverable exception: `catch @panic("oops");`
- Zababa 5y agoThat's nice. Are the sum types checked by the compiler to ensure that you didn't miss any case?
- squeek502 5y agoIf 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) { ^
- Zababa 5y agoYou did understand it correctly. That's a really nice feature.
- AndyKelley 5y agoYes, 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/7d0de54ad44832589379a4bcbba493db2087bebf/src/Module.zig#L2327-L2355 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).
- Zababa 5y agoThat's a great feature. I'm constantly impressed by what Zig can do.
- Gaelan 5y agoThis 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.)
- randyrand 5y agoC has always had Asserts for that reason.
- Zababa 5y agoIs it idiomatic to assert things and recover from them the way people sometimes do with exceptions?