| ... | ... | @@ -5584,7 +5584,7 @@ fn doAThing(str: []u8) !void { |
| 5584 | 5584 | appropriately. |
| 5585 | 5585 | </p> |
| 5586 | 5586 | <p> |
| 5587 | | Finally, you may want to take a different action for every situation. For that, we combine |
| 5587 | You may want to take a different action for every situation. For that, we combine |
| 5588 | 5588 | the {#link|if#} and {#link|switch#} expression: |
| 5589 | 5589 | </p> |
| 5590 | 5590 | {#syntax_block|zig|handle_all_error_scenarios.zig#} |
| ... | ... | @@ -5598,6 +5598,22 @@ fn doAThing(str: []u8) void { |
| 5598 | 5598 | // we promise that InvalidChar won't happen (or crash in debug mode if it does) |
| 5599 | 5599 | error.InvalidChar => unreachable, |
| 5600 | 5600 | } |
| 5601 | } |
| 5602 | {#end_syntax_block#} |
| 5603 | <p> |
| 5604 | Finally, you may want to handle only some errors. For that, you can capture the unhandled |
| 5605 | errors in the {#syntax#}else{#endsyntax#} case, which now contains a narrower error set: |
| 5606 | </p> |
| 5607 | {#syntax_block|zig|handle_some_error_scenarios.zig#} |
| 5608 | fn doAnotherThing(str: []u8) error{InvaidChar}!void { |
| 5609 | if (parseU64(str, 10)) |number| { |
| 5610 | doSomethingWithNumber(number); |
| 5611 | } else |err| switch (err) { |
| 5612 | error.Overflow => { |
| 5613 | // handle overflow... |
| 5614 | }, |
| 5615 | else => |leftover_err| return leftover_err, |
| 5616 | } |
| 5601 | 5617 | } |
| 5602 | 5618 | {#end_syntax_block#} |
| 5603 | 5619 | <p> |