024_errors4.zig 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 a temporary hack to deal with
  21. // makeJustRight()'s returned error union (for now).
  22. const a: u32 = makeJustRight(44) catch 0;
  23. const b: u32 = makeJustRight(14) catch 0;
  24. const 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) catch |err|{
  56. if(err == MyNumberError.TooSmall){
  57. return 10;
  58. }
  59. return err;
  60. };
  61. }
  62. fn detectProblems(n: u32) MyNumberError!u32{
  63. if(n < 10){ return MyNumberError.TooSmall; }
  64. if(n > 20){ return MyNumberError.TooBig; }
  65. return n;
  66. }