025_errors5.zig 858 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // Zig has a handy "try" shortcut for this common error handling pattern:
  3. //
  4. // canFail() catch |err| return err;
  5. //
  6. // which can be more compactly written as:
  7. //
  8. // try canFail();
  9. //
  10. const std = @import("std");
  11. const MyNumberError = error{
  12. TooSmall,
  13. TooBig,
  14. };
  15. pub fn main() void {
  16. var a: u32 = addFive(44) catch 0;
  17. var b: u32 = addFive(14) catch 0;
  18. var c: u32 = addFive(4) catch 0;
  19. std.debug.print("a={}, b={}, c={}\n", .{ a, b, c });
  20. }
  21. fn addFive(n: u32) MyNumberError!u32 {
  22. // This function needs to return any error which might come back from detect().
  23. // Please use a "try" statement rather than a "catch".
  24. //
  25. var x = detect(n);
  26. return x + 5;
  27. }
  28. fn detect(n: u32) MyNumberError!u32 {
  29. if (n < 10) return MyNumberError.TooSmall;
  30. if (n > 20) return MyNumberError.TooBig;
  31. return n;
  32. }