Errors and try in Zig
Errors are values in the return type: a vault that either opens or says why not.
const std = @import("std");
const VaultError = error{WrongCombination};
fn open(guess: u32) VaultError![]const u8 {
if (guess == 628) return "deed to the tin mine";
return VaultError.WrongCombination;
}
pub fn main() !void {
// try unwraps a success or returns the error to the caller.
const prize = try open(628);
std.debug.print("inside: {s}\n", .{prize});
// if with an else-capture inspects the failure instead.
if (open(111)) |p| {
std.debug.print("inside: {s}\n", .{p});
} else |err| {
std.debug.print("no luck: {s}\n", .{@errorName(err)});
}
}
How it works
error{WrongCombination}declares the error set;!puts it in the return type.try open(628)unwraps success or returns the error up the stack.if (...) |p| ... else |err|captures whichever side actually happened.
Keywords and builtins used here
constelseerrorfnifpubreturntryu32u8void
The run, in numbers
- Lines
- 20
- Characters to type
- 553
- Tokens
- 142
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 122 seconds.
Step 1 of 3 in Errors, step 7 of 27 in Language basics.