033_iferror.zig 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // Let's revisit the very first error exercise. This time, we're going to
  3. // look at an error-handling variation of the "if" statement.
  4. //
  5. // if (foo) |value| {
  6. //
  7. // // foo was NOT an error; value is the non-error value of foo
  8. //
  9. // } else |err| {
  10. //
  11. // // foo WAS an error; err is the error value of foo
  12. //
  13. // }
  14. //
  15. // We'll take it even further and use a switch statement to handle
  16. // the error types.
  17. //
  18. // if (foo) |value| {
  19. // ...
  20. // } else |err| switch (err) {
  21. // ...
  22. // }
  23. //
  24. const MyNumberError = error{
  25. TooBig,
  26. TooSmall,
  27. };
  28. const std = @import("std");
  29. pub fn main() void {
  30. const nums = [_]u8{ 2, 3, 4, 5, 6 };
  31. for (nums) |num| {
  32. std.debug.print("{}", .{num});
  33. const n = numberMaybeFail(num);
  34. if (n) |value| {
  35. std.debug.print("={}. ", .{value});
  36. } else |err| switch (err) {
  37. MyNumberError.TooBig => std.debug.print(">4. ", .{}),
  38. // Please add a match for TooSmall here and have it print: "<4. "
  39. }
  40. }
  41. std.debug.print("\n", .{});
  42. }
  43. // This time we'll have numberMaybeFail() return an error union rather
  44. // than a straight error.
  45. fn numberMaybeFail(n: u8) MyNumberError!u8 {
  46. if (n > 4) return MyNumberError.TooBig;
  47. if (n < 4) return MyNumberError.TooSmall;
  48. return n;
  49. }