033_iferror.zig 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // Let's revisit the very first error exercise. This time, we're going to
  3. // look at a special error-handling type 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. const MyNumberError = error{
  19. TooBig,
  20. TooSmall,
  21. };
  22. const std = @import("std");
  23. pub fn main() void {
  24. var nums = [_]u8{ 2, 3, 4, 5, 6 };
  25. for (nums) |num| {
  26. std.debug.print("{}", .{num});
  27. var n = numberMaybeFail(num);
  28. if (n) |value| {
  29. std.debug.print("={}. ", .{value});
  30. } else |err| switch (err) {
  31. MyNumberError.TooBig => std.debug.print(">4. ", .{}),
  32. // Please add a match for TooSmall here and have it print: "<4. "
  33. }
  34. }
  35. std.debug.print("\n", .{});
  36. }
  37. // This time we'll have numberMaybeFail() return an error union rather
  38. // than a straight error.
  39. fn numberMaybeFail(n: u8) MyNumberError!u8 {
  40. if (n > 4) return MyNumberError.TooBig;
  41. if (n < 4) return MyNumberError.TooSmall;
  42. return n;
  43. }