authorgravatar for sbensu@gmail.comSebastian Bensusan <sbensu@gmail.com> 2023-06-21 17:39:14-04:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-06-23 01:09:04+03:00
log64faaa7d8fe551ae3a1c20062b4c63f528b937eb
tree4fa99b19d5e5c2ab34788e37af90593bc015bfd2
parent6aa88ecc54fde57af893456e9e5fcea5b3e1cb03

Langref: Add example for catching some errors and narrowing the error set


1 files changed, 17 insertions(+), 1 deletions(-)

doc/langref.html.in+17-1
...@@ -5584,7 +5584,7 @@ fn doAThing(str: []u8) !void {...@@ -5584,7 +5584,7 @@ fn doAThing(str: []u8) !void {
5584 appropriately.5584 appropriately.
5585 </p>5585 </p>
5586 <p>5586 <p>
5587 Finally, you may want to take a different action for every situation. For that, we combine5587 You may want to take a different action for every situation. For that, we combine
5588 the {#link|if#} and {#link|switch#} expression:5588 the {#link|if#} and {#link|switch#} expression:
5589 </p>5589 </p>
5590 {#syntax_block|zig|handle_all_error_scenarios.zig#}5590 {#syntax_block|zig|handle_all_error_scenarios.zig#}
...@@ -5598,6 +5598,22 @@ fn doAThing(str: []u8) void {...@@ -5598,6 +5598,22 @@ fn doAThing(str: []u8) void {
5598 // we promise that InvalidChar won't happen (or crash in debug mode if it does)5598 // we promise that InvalidChar won't happen (or crash in debug mode if it does)
5599 error.InvalidChar => unreachable,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 {#end_syntax_block#}5618 {#end_syntax_block#}
5603 <p>5619 <p>