Skip to content

Commit

Permalink
langref: add example for errdefer |err| sytnax
Browse files Browse the repository at this point in the history
  • Loading branch information
matklad committed Jul 1, 2024
1 parent 726ff55 commit f795858
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/langref.html.in
Original file line number Diff line number Diff line change
Expand Up @@ -2984,6 +2984,10 @@ fn createFoo(param: i32) !Foo {
}
{#end_syntax_block#}
<p>
The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error:
</p>
{#code|test_errdefer_capture.zig#}
<p>
The neat thing about this is that you get robust error handling without
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.
Expand Down
19 changes: 19 additions & 0 deletions doc/langref/test_errdefer_capture.zig
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit f795858

Please sign in to comment.