ziglings/exercises/025_errors5.zig

39 lines
866 B
Zig
Raw Normal View History

2021-01-30 20:00:32 -05:00
//
// 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 {
2023-06-22 05:41:41 -04:00
const a: u32 = addFive(44) catch 0;
const b: u32 = addFive(14) catch 0;
const c: u32 = addFive(4) catch 0;
2021-01-30 20:00:32 -05:00
std.debug.print("a={}, b={}, c={}\n", .{ a, b, c });
2021-01-30 20:00:32 -05:00
}
fn addFive(n: u32) MyNumberError!u32 {
2021-02-12 02:39:30 -05:00
// This function needs to return any error which might come back from detect().
2021-01-30 20:00:32 -05:00
// Please use a "try" statement rather than a "catch".
//
const x = detect(n);
2021-01-30 20:00:32 -05:00
return x + 5;
}
fn detect(n: u32) MyNumberError!u32 {
if (n < 10) return MyNumberError.TooSmall;
if (n > 20) return MyNumberError.TooBig;
return n;
}