From 8328f5ed51aee877dfc616be5d6fdcaa09becdca Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Tue, 17 May 2022 18:34:28 +0200 Subject: [PATCH 1/2] docs: add documentation about return stm in the defer method Signed-off-by: Vincenzo Palazzo --- doc/langref.html.in | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/doc/langref.html.in b/doc/langref.html.in index 32320d5113..feee376e4e 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -4813,6 +4813,19 @@ fn deferErrorExample(is_error: bool) !void { print("encountered an error!\n", .{}); } + // inside a defer method the return statement + // is not allowed. + // The following lines produce the following + // error if uncomment + // ``` + // defer.zig:73:9: error: cannot return from defer expression + // return error.DeferError; + // ``` + // + //defer { + // return error.DeferError; + //} + if (is_error) { return error.DeferError; } From 80f3c8d2761bb09ccb43d667e6d2c5f73cf408bc Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Tue, 17 May 2022 21:03:42 +0200 Subject: [PATCH 2/2] docs: add documentation on errdefer with caputure syntax Signed-off-by: Vincenzo Palazzo --- doc/langref.html.in | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/langref.html.in b/doc/langref.html.in index feee376e4e..839b5ed3bf 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -4831,9 +4831,23 @@ fn deferErrorExample(is_error: bool) !void { } } +// The errdefer keyword support also an alternative syntax to capture the +// error generated in case of one error. +// +// This is useful when during the clean up after an error additional +// message want to be printed. +fn deferErrorCaptureExample() !void { + errdefer |err| { + std.debug.print("the error is {s}\n", .{@errorName(err)}); + } + + return error.DeferError; +} + test "errdefer unwinding" { deferErrorExample(false) catch {}; deferErrorExample(true) catch {}; + deferErrorCaptureExample() catch {}; } {#code_end#} {#see_also|Errors#} @@ -11941,7 +11955,7 @@ fn readU32Be() u32 {}
{#syntax#}errdefer{#endsyntax#}
- {#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error. + {#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error, the errdefer expression can capture the unwrapped value.
  • See also {#link|errdefer#}