| ... | @@ -5452,6 +5452,22 @@ fn doAThing(str: []u8) void { | ... | @@ -5452,6 +5452,22 @@ fn doAThing(str: []u8) void { |
| 5452 | a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must | 5452 | a default value of 13. The type of the right hand side of the binary {#syntax#}catch{#endsyntax#} operator must |
| 5453 | match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}. | 5453 | match the unwrapped error union type, or be of type {#syntax#}noreturn{#endsyntax#}. |
| 5454 | </p> | 5454 | </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#} |
| | 5461 | const parseU64 = @import("error_union_parsing_u64.zig").parseU64; |
| | 5462 | |
| | 5463 | fn 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#} |
| 5455 | {#header_close#} | 5471 | {#header_close#} |
| 5456 | {#header_open|try#} | 5472 | {#header_open|try#} |
| 5457 | <p>Let's say you wanted to return the error if you got one, otherwise continue with the | 5473 | <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 { | ... | @@ -5509,6 +5525,20 @@ fn doAThing(str: []u8) void { |
| 5509 | // we promise that InvalidChar won't happen (or crash in debug mode if it does) | 5525 | // we promise that InvalidChar won't happen (or crash in debug mode if it does) |
| 5510 | error.InvalidChar => unreachable, | 5526 | error.InvalidChar => unreachable, |
| 5511 | } | 5527 | } |
| | 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#} |
| | 5536 | fn doADifferentThing(str: []u8) void { |
| | 5537 | if (parseU64(str, 10)) |number| { |
| | 5538 | doSomethingWithNumber(number); |
| | 5539 | } else |_| { |
| | 5540 | // do as you'd like |
| | 5541 | } |
| 5512 | } | 5542 | } |
| 5513 | {#end_syntax_block#} | 5543 | {#end_syntax_block#} |
| 5514 | {#header_open|errdefer#} | 5544 | {#header_open|errdefer#} |