025_errors5.zig 848 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. const a: u32 = addFive(44) catch 0;
  17. const b: u32 = addFive(14) catch 0;
  18. const 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. const x = try 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. }