021_errors.zig 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // Believe it or not, sometimes things go wrong in programs.
  3. //
  4. // In Zig, an error is a value. Errors are named so we can identify
  5. // things that can go wrong. Errors are created in "error sets", which
  6. // are just a collection of named errors.
  7. //
  8. // We have the start of an error set, but we're missing the condition
  9. // "TooSmall". Please add it where needed!
  10. const MyNumberError = error{
  11. TooBig,
  12. ???,
  13. TooFour,
  14. };
  15. const std = @import("std");
  16. pub fn main() void {
  17. var nums = [_]u8{ 2, 3, 4, 5, 6 };
  18. for (nums) |n| {
  19. std.debug.print("{}", .{n});
  20. const number_error = numberFail(n);
  21. if (number_error == MyNumberError.TooBig) {
  22. std.debug.print(">4. ", .{});
  23. }
  24. if (???) {
  25. std.debug.print("<4. ", .{});
  26. }
  27. if (number_error == MyNumberError.TooFour) {
  28. std.debug.print("=4. ", .{});
  29. }
  30. }
  31. std.debug.print("\n", .{});
  32. }
  33. // Notice how this function can return any member of the MyNumberError
  34. // error set.
  35. fn numberFail(n: u8) MyNumberError {
  36. if (n > 4) return MyNumberError.TooBig;
  37. if (n < 4) return MyNumberError.TooSmall; // <---- this one is free!
  38. return MyNumberError.TooFour;
  39. }