diff --git a/doc/langref.html.in b/doc/langref.html.in index aa606abd69fa..f0b775a04310 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -2988,6 +2988,10 @@ fn createFoo(param: i32) !Foo { 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.

+

+ The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error: +

+ {#code|test_errdefer_capture.zig#} {#header_close#} {#header_open|Common errdefer Slip-Ups#}

diff --git a/doc/langref/test_errdefer_capture.zig b/doc/langref/test_errdefer_capture.zig new file mode 100644 index 000000000000..26be5269bdeb --- /dev/null +++ b/doc/langref/test_errdefer_capture.zig @@ -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