diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-01-30 20:00:32 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-01-30 20:00:32 -0500 |
commit | 2de8a8c54d7090dd063bed8b6b283c2fcb452e43 (patch) | |
tree | 80c1fc20d0a171aef52d0fbd0ccaa99409b3e63f /21_errors.zig | |
parent | 08ec029f20381580ebe76ad8bd3feca2e5cd262a (diff) | |
download | ziglings-2de8a8c54d7090dd063bed8b6b283c2fcb452e43.tar.gz ziglings-2de8a8c54d7090dd063bed8b6b283c2fcb452e43.tar.bz2 ziglings-2de8a8c54d7090dd063bed8b6b283c2fcb452e43.tar.xz ziglings-2de8a8c54d7090dd063bed8b6b283c2fcb452e43.zip |
Added ex 21-26 for error handling
Diffstat (limited to '21_errors.zig')
-rw-r--r-- | 21_errors.zig | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/21_errors.zig b/21_errors.zig new file mode 100644 index 0000000..34c5e18 --- /dev/null +++ b/21_errors.zig @@ -0,0 +1,46 @@ +// +// Believe it or not, sometimes things to wrong in programs. +// +// In Zig, an error is a value. Errors are named so we can identify +// things that can go wrong. Errors are created in "error sets", which +// are just a collection of named errors. +// +// We have the start of an error set, but we're missing the condition +// "TooSmall". Please add it where needed! +const MyNumberError = error{ + TooBig, + ???, + TooFour, +}; + +const std = @import("std"); + +pub fn main() void { + var nums = [_]u8{2,3,4,5,6}; + + for (nums) |n| { + std.debug.print("{}", .{n}); + + const number_error = numberFail(n); + + if (number_error == MyNumberError.TooBig) { + std.debug.print(">4. ", .{}); + } + if (???) { + std.debug.print("<4. ", .{}); + } + if (number_error == MyNumberError.TooFour) { + std.debug.print("=4. ", .{}); + } + } + + std.debug.print("\n", .{}); +} + +// Notice how this function can return any member of the MyNumberError +// error set. +fn numberFail(n: u8) MyNumberError { + if(n > 4) return MyNumberError.TooBig; + if(n < 4) return MyNumberError.TooSmall; // <---- this one is free! + return MyNumberError.TooFour; +} |