From f79585845042613f8855476c2c4421802aa90866 Mon Sep 17 00:00:00 2001 From: Alex Kladov Date: Fri, 28 Jun 2024 13:32:56 +0100 Subject: [PATCH] langref: add example for errdefer |err| sytnax --- doc/langref.html.in | 4 ++++ doc/langref/test_errdefer_capture.zig | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 doc/langref/test_errdefer_capture.zig 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