aboutsummaryrefslogtreecommitdiff
path: root/exercises/25_errors5.zig
diff options
context:
space:
mode:
authorDave Gauer <dave@ratfactor.com>2021-02-09 18:36:57 -0500
committerDave Gauer <dave@ratfactor.com>2021-02-09 18:36:57 -0500
commit55ad7c32f2d534b1fbd438204d21738f958c51a5 (patch)
tree16be4b53193105a759b3eec25be5e664d41c428d /exercises/25_errors5.zig
parentcf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907 (diff)
downloadziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.gz
ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.bz2
ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.xz
ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.zip
Moved exercises to exercises because exercises
Diffstat (limited to 'exercises/25_errors5.zig')
-rw-r--r--exercises/25_errors5.zig40
1 files changed, 40 insertions, 0 deletions
diff --git a/exercises/25_errors5.zig b/exercises/25_errors5.zig
new file mode 100644
index 0000000..d9e9ce1
--- /dev/null
+++ b/exercises/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;
+}
+