From 6ad9774189fbd64b2f2c9519f4513ab34b0c3809 Mon Sep 17 00:00:00 2001 From: Dave Gauer Date: Fri, 12 Mar 2021 18:59:46 -0500 Subject: "999 is enough for anybody" triple-zero padding (#18) When I hit 999 exercises, I will finally have reached the ultimate state of soteriological release and no more exercises will be needed. The cycle will be complete. All that will be left is perfect quietude, freedom, and highest happiness. --- exercises/025_errors5.zig | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 exercises/025_errors5.zig (limited to 'exercises/025_errors5.zig') diff --git a/exercises/025_errors5.zig b/exercises/025_errors5.zig new file mode 100644 index 0000000..5119dcf --- /dev/null +++ b/exercises/025_errors5.zig @@ -0,0 +1,38 @@ +// +// 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 detect(). + // 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; +} -- cgit v1.2.3-ZIG