diff options
| author | Phil Eaton <phil@eatonphil.com> | 2023-03-23 05:06:46 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-03-23 10:06:46 +0100 |
| commit | 38ee46dda31101f349ea9eee762908f924fd384c (patch) | |
| tree | 67ccf0a4e8cfa4fe324cae3d5d3984adbb4cec0a /doc/langref.html.in | |
| parent | 9fedecf4ab6035dca596648cd31ce85798ad69d5 (diff) | |
| download | zig-38ee46dda31101f349ea9eee762908f924fd384c.tar.gz zig-38ee46dda31101f349ea9eee762908f924fd384c.zip | |
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
Diffstat (limited to 'doc/langref.html.in')
| -rw-r--r-- | doc/langref.html.in | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/doc/langref.html.in b/doc/langref.html.in index be055c3179..907464867e 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -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 match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}. </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_open|try#} <p>Let's say you wanted to return the error if you got one, otherwise continue with the @@ -5511,6 +5527,20 @@ fn doAThing(str: []u8) void { } } {#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#} {#header_open|errdefer#} <p> The other component to error handling is defer statements. |
