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 /25_errors5.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 '25_errors5.zig')
-rw-r--r-- | 25_errors5.zig | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/25_errors5.zig b/25_errors5.zig new file mode 100644 index 0000000..d9e9ce1 --- /dev/null +++ b/25_errors5.zig @@ -0,0 +1,40 @@ +// +// Zig has a handy "try" shortcut for this common error handling pattern: +// +// canFail() catch |err| return err; +// +// which can be more compactly written as: +// +// try canFail(); +// +const std = @import("std"); + +const MyNumberError = error{ + TooSmall, + TooBig, +}; + +pub fn main() void { + var a: u32 = addFive(44) catch 0; + var b: u32 = addFive(14) catch 0; + var c: u32 = addFive(4) catch 0; + + std.debug.print("a={}, b={}, c={}", .{a,b,c}); +} + +fn addFive(n: u32) MyNumberError!u32 { + // + // This function needs to return any error which might come back from fix(). + // Please use a "try" statement rather than a "catch". + // + var x = detect(n); + + return x + 5; +} + +fn detect(n: u32) MyNumberError!u32 { + if (n < 10) return MyNumberError.TooSmall; + if (n > 20) return MyNumberError.TooBig; + return n; +} + |