diff --git a/doc/langref.html.in b/doc/langref.html.in index f64998efe2f0..c76d8bca8ec1 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -2984,6 +2984,10 @@ fn createFoo(param: i32) !Foo { } {#end_syntax_block#}
+ The {#syntax#}errdefer{#endsyntax#} statement can optionally capture the error: +
+ {#code|test_errdefer_capture.zig#} +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. 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