mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
langref: add example for errdefer |err| sytnax
This commit is contained in:
parent
aa73bb6bc9
commit
8267929742
2 changed files with 23 additions and 0 deletions
|
|
@ -2992,6 +2992,10 @@ fn createFoo(param: i32) !Foo {
|
||||||
the verbosity and cognitive overhead of trying to make sure every exit path
|
the verbosity and cognitive overhead of trying to make sure every exit path
|
||||||
is covered. The deallocation code is always directly following the allocation code.
|
is covered. The deallocation code is always directly following the allocation code.
|
||||||
</p>
|
</p>
|
||||||
|
<p>
|
||||||
|
The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error:
|
||||||
|
</p>
|
||||||
|
{#code|test_errdefer_capture.zig#}
|
||||||
{#header_close#}
|
{#header_close#}
|
||||||
{#header_open|Common errdefer Slip-Ups#}
|
{#header_open|Common errdefer Slip-Ups#}
|
||||||
<p>
|
<p>
|
||||||
|
|
|
||||||
19
doc/langref/test_errdefer_capture.zig
Normal file
19
doc/langref/test_errdefer_capture.zig
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
fn captureError(captured: *?anyerror) !void {
|
||||||
|
errdefer |err| {
|
||||||
|
captured.* = err;
|
||||||
|
}
|
||||||
|
return error.GeneralFailure;
|
||||||
|
}
|
||||||
|
|
||||||
|
test "errdefer capture" {
|
||||||
|
var captured: ?anyerror = null;
|
||||||
|
|
||||||
|
if (captureError(&captured)) unreachable else |err| {
|
||||||
|
try std.testing.expectEqual(error.GeneralFailure, captured.?);
|
||||||
|
try std.testing.expectEqual(error.GeneralFailure, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// test
|
||||||
Loading…
Add table
Reference in a new issue