024_errors4.zig 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Using `catch` to replace an error with a default value is a bit
  3. // of a blunt instrument since it doesn't matter what the error is.
  4. //
  5. // Catch lets us capture the error value and perform additional
  6. // actions with this form:
  7. //
  8. // canFail() catch |err| {
  9. // if (err == FishError.TunaMalfunction) {
  10. // ...
  11. // }
  12. // };
  13. //
  14. const std = @import("std");
  15. const MyNumberError = error{
  16. TooSmall,
  17. TooBig,
  18. };
  19. pub fn main() void {
  20. // The "catch 0" below is just our way of dealing with the fact
  21. // that makeJustRight() returns a error union (for now).
  22. var a: u32 = makeJustRight(44) catch 0;
  23. var b: u32 = makeJustRight(14) catch 0;
  24. var c: u32 = makeJustRight(4) catch 0;
  25. std.debug.print("a={}, b={}, c={}\n", .{ a, b, c });
  26. }
  27. // In this silly example we've split the responsibility of making
  28. // a number just right into four (!) functions:
  29. //
  30. // makeJustRight() Calls fixTooBig(), cannot fix any errors.
  31. // fixTooBig() Calls fixTooSmall(), fixes TooBig errors.
  32. // fixTooSmall() Calls detectProblems(), fixes TooSmall errors.
  33. // detectProblems() Returns the number or an error.
  34. //
  35. fn makeJustRight(n: u32) MyNumberError!u32 {
  36. return fixTooBig(n) catch |err| {
  37. return err;
  38. };
  39. }
  40. fn fixTooBig(n: u32) MyNumberError!u32 {
  41. return fixTooSmall(n) catch |err| {
  42. if (err == MyNumberError.TooBig) {
  43. return 20;
  44. }
  45. return err;
  46. };
  47. }
  48. fn fixTooSmall(n: u32) MyNumberError!u32 {
  49. // Oh dear, this is missing a lot! But don't worry, it's nearly
  50. // identical to fixTooBig() above.
  51. //
  52. // If we get a TooSmall error, we should return 10.
  53. // If we get any other error, we should return that error.
  54. // Otherwise, we return the u32 number.
  55. return detectProblems(n) ???
  56. }
  57. fn detectProblems(n: u32) MyNumberError!u32 {
  58. if (n < 10) return MyNumberError.TooSmall;
  59. if (n > 20) return MyNumberError.TooBig;
  60. return n;
  61. }