24_errors4.zig 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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={}", .{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| { return err; };
  37. }
  38. fn fixTooBig(n: u32) MyNumberError!u32 {
  39. return fixTooSmall(n) catch |err| {
  40. if (err == MyNumberError.TooBig) {
  41. return 20;
  42. }
  43. return err;
  44. };
  45. }
  46. fn fixTooSmall(n: u32) MyNumberError!u32 {
  47. // Oh dear, this is missing a lot! But don't worry, it's nearly
  48. // identical to fixTooBig() above.
  49. //
  50. // If we get a TooSmall error, we should return 10.
  51. // If we get any other error, we should return that error.
  52. // Otherwise, we return the u32 number.
  53. return detectProblems(n) ???
  54. }
  55. fn detectProblems(n: u32) MyNumberError!u32 {
  56. if (n < 10) return MyNumberError.TooSmall;
  57. if (n > 20) return MyNumberError.TooBig;
  58. return n;
  59. }