25_errors5.zig 861 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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={}", .{a,b,c});
  20. }
  21. fn addFive(n: u32) MyNumberError!u32 {
  22. //
  23. // This function needs to return any error which might come back from detect().
  24. // Please use a "try" statement rather than a "catch".
  25. //
  26. var x = detect(n);
  27. return x + 5;
  28. }
  29. fn detect(n: u32) MyNumberError!u32 {
  30. if (n < 10) return MyNumberError.TooSmall;
  31. if (n > 20) return MyNumberError.TooBig;
  32. return n;
  33. }