authorgravatar for phil@eatonphil.comPhil Eaton <phil@eatonphil.com> 2023-03-23 05:06:46-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-03-23 10:06:46+01:00
log38ee46dda31101f349ea9eee762908f924fd384c
tree67ccf0a4e8cfa4fe324cae3d5d3984adbb4cec0a
parent9fedecf4ab6035dca596648cd31ce85798ad69d5
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Two more examples of possible syntax when dealing with errors (#15042)

Add an example of if with try without else switch; add example of catch with block returning value

1 files changed, 30 insertions(+), 0 deletions(-)

doc/langref.html.in+30
......@@ -5452,6 +5452,22 @@ fn doAThing(str: []u8) void {
54525452 a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must
54535453 match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}.
54545454 </p>
5455 <p>
5456 If you want to provide a default value with
5457 {#syntax#}catch{#endsyntax#} after performing some logic, you
5458 can combine {#syntax#}catch{#endsyntax#} with named {#link|Blocks#}:
5459 </p>
5460 {#code_begin|syntax|handle_error_with_catch_block.zig#}
5461const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
5462
5463fn doAThing(str: []u8) void {
5464 const number = parseU64(str, 10) catch blk: {
5465 // do things
5466 break :blk 13;
5467 };
5468 _ = number; // number is now initialized
5469}
5470 {#code_end#}
54555471 {#header_close#}
54565472 {#header_open|try#}
54575473 <p>Let's say you wanted to return the error if you got one, otherwise continue with the
......@@ -5509,6 +5525,20 @@ fn doAThing(str: []u8) void {
55095525 // we promise that InvalidChar won't happen (or crash in debug mode if it does)
55105526 error.InvalidChar => unreachable,
55115527 }
5528}
5529 {#end_syntax_block#}
5530 <p>
5531 You must use the variable capture syntax. If you don't need the
5532 variable, you can capture with {#syntax#}_{#endsyntax#} and avoid the
5533 {#syntax#}switch{#endsyntax#}.
5534 </p>
5535 {#syntax_block|zig|handle_no_error_scenarios.zig#}
5536fn doADifferentThing(str: []u8) void {
5537 if (parseU64(str, 10)) |number| {
5538 doSomethingWithNumber(number);
5539 } else |_| {
5540 // do as you'd like
5541 }
55125542}
55135543 {#end_syntax_block#}
55145544 {#header_open|errdefer#}