From 64faaa7d8fe551ae3a1c20062b4c63f528b937eb Mon Sep 17 00:00:00 2001 From: Sebastian Bensusan Date: Wed, 21 Jun 2023 17:39:14 -0400 Subject: [PATCH] Langref: Add example for catching some errors and narrowing the error set --- doc/langref.html.in | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index 392bfe2bbc..0b37db1997 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -5584,7 +5584,7 @@ fn doAThing(str: []u8) !void { appropriately.

- Finally, you may want to take a different action for every situation. For that, we combine + You may want to take a different action for every situation. For that, we combine the {#link|if#} and {#link|switch#} expression:

{#syntax_block|zig|handle_all_error_scenarios.zig#} @@ -5598,6 +5598,22 @@ fn doAThing(str: []u8) void { // we promise that InvalidChar won't happen (or crash in debug mode if it does) error.InvalidChar => unreachable, } +} + {#end_syntax_block#} +

+ Finally, you may want to handle only some errors. For that, you can capture the unhandled + errors in the {#syntax#}else{#endsyntax#} case, which now contains a narrower error set: +

+ {#syntax_block|zig|handle_some_error_scenarios.zig#} + fn doAnotherThing(str: []u8) error{InvaidChar}!void { + if (parseU64(str, 10)) |number| { + doSomethingWithNumber(number); + } else |err| switch (err) { + error.Overflow => { + // handle overflow... + }, + else => |leftover_err| return leftover_err, + } } {#end_syntax_block#}