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
This commit is contained in:
Phil Eaton 2023-03-23 05:06:46 -04:00 committed by GitHub
parent 9fedecf4ab
commit 38ee46dda3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5452,6 +5452,22 @@ fn doAThing(str: []u8) void {
a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must
match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}. match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}.
</p> </p>
<p>
If you want to provide a default value with
{#syntax#}catch{#endsyntax#} after performing some logic, you
can combine {#syntax#}catch{#endsyntax#} with named {#link|Blocks#}:
</p>
{#code_begin|syntax|handle_error_with_catch_block.zig#}
const parseU64 = @import("error_union_parsing_u64.zig").parseU64;
fn doAThing(str: []u8) void {
const number = parseU64(str, 10) catch blk: {
// do things
break :blk 13;
};
_ = number; // number is now initialized
}
{#code_end#}
{#header_close#} {#header_close#}
{#header_open|try#} {#header_open|try#}
<p>Let's say you wanted to return the error if you got one, otherwise continue with the <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 {
// we promise that InvalidChar won't happen (or crash in debug mode if it does) // we promise that InvalidChar won't happen (or crash in debug mode if it does)
error.InvalidChar => unreachable, error.InvalidChar => unreachable,
} }
}
{#end_syntax_block#}
<p>
You must use the variable capture syntax. If you don't need the
variable, you can capture with {#syntax#}_{#endsyntax#} and avoid the
{#syntax#}switch{#endsyntax#}.
</p>
{#syntax_block|zig|handle_no_error_scenarios.zig#}
fn doADifferentThing(str: []u8) void {
if (parseU64(str, 10)) |number| {
doSomethingWithNumber(number);
} else |_| {
// do as you'd like
}
} }
{#end_syntax_block#} {#end_syntax_block#}
{#header_open|errdefer#} {#header_open|errdefer#}