diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-02-09 18:36:57 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-02-09 18:36:57 -0500 |
commit | 55ad7c32f2d534b1fbd438204d21738f958c51a5 (patch) | |
tree | 16be4b53193105a759b3eec25be5e664d41c428d /29_errdefer.zig | |
parent | cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907 (diff) | |
download | ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.gz ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.bz2 ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.tar.xz ziglings-55ad7c32f2d534b1fbd438204d21738f958c51a5.zip |
Moved exercises to exercises because exercises
Diffstat (limited to '29_errdefer.zig')
-rw-r--r-- | 29_errdefer.zig | 60 |
1 files changed, 0 insertions, 60 deletions
diff --git a/29_errdefer.zig b/29_errdefer.zig deleted file mode 100644 index cd2158d..0000000 --- a/29_errdefer.zig +++ /dev/null @@ -1,60 +0,0 @@ -// -// Another common problem is a block of code that could exit in multiple -// places due to an error - but that needs to run do something before it -// exits (typically to clean up after itself). -// -// An "errdefer" is a defer that only runs if the block exits with an error: -// -// { -// errdefer cleanup(); -// try canFail(); -// } -// -// The cleanup() function is called ONLY if the "try" statement returns an -// error produced by canFail(). -// -const std = @import("std"); - -// -var counter: u32 = 0; - -const MyErr = error{ GetFail, IncFail }; - -pub fn main() void { - // We simply quit the entire program if we fail to get a number: - var a: u32 = makeNumber() catch return; - var b: u32 = makeNumber() catch return; - - std.debug.print("Numbers: {}, {}\n", .{a,b}); -} - -fn makeNumber() MyErr!u32 { - std.debug.print("Getting number...", .{}); - - // Please make the "failed" message print ONLY if the makeNumber() - // function exits with an error: - std.debug.print("failed!\n", .{}); - - var num = try getNumber(); // <-- This could fail! - - num = try increaseNumber(num); // <-- This could ALSO fail! - - std.debug.print("got {}. ", .{num}); - - return num; -} - -fn getNumber() MyErr!u32 { - // I _could_ fail...but I don't! - return 4; -} - -fn increaseNumber(n: u32) MyErr!u32 { - // I fail after the first time you run me! - if (counter > 0) return MyErr.IncFail; - - // Sneaky, weird global stuff. - counter += 1; - - return n + 1; -} |