| ... | ... | @@ -4862,14 +4862,41 @@ fn deferErrorExample(is_error: bool) !void { |
| 4862 | 4862 | print("encountered an error!\n", .{}); |
| 4863 | 4863 | } |
| 4864 | 4864 | |
| 4865 | // inside a defer method the return statement |
| 4866 | // is not allowed. |
| 4867 | // The following lines produce the following |
| 4868 | // error if uncomment |
| 4869 | // ``` |
| 4870 | // defer.zig:73:9: error: cannot return from defer expression |
| 4871 | // return error.DeferError; |
| 4872 | // ``` |
| 4873 | // |
| 4874 | //defer { |
| 4875 | // return error.DeferError; |
| 4876 | //} |
| 4877 | |
| 4865 | 4878 | if (is_error) { |
| 4866 | 4879 | return error.DeferError; |
| 4867 | 4880 | } |
| 4868 | 4881 | } |
| 4869 | 4882 | |
| 4883 | // The errdefer keyword support also an alternative syntax to capture the |
| 4884 | // error generated in case of one error. |
| 4885 | // |
| 4886 | // This is useful when during the clean up after an error additional |
| 4887 | // message want to be printed. |
| 4888 | fn deferErrorCaptureExample() !void { |
| 4889 | errdefer |err| { |
| 4890 | std.debug.print("the error is {s}\n", .{@errorName(err)}); |
| 4891 | } |
| 4892 | |
| 4893 | return error.DeferError; |
| 4894 | } |
| 4895 | |
| 4870 | 4896 | test "errdefer unwinding" { |
| 4871 | 4897 | deferErrorExample(false) catch {}; |
| 4872 | 4898 | deferErrorExample(true) catch {}; |
| 4899 | deferErrorCaptureExample() catch {}; |
| 4873 | 4900 | } |
| 4874 | 4901 | {#code_end#} |
| 4875 | 4902 | {#see_also|Errors#} |
| ... | ... | @@ -11930,7 +11957,7 @@ fn readU32Be() u32 {} |
| 11930 | 11957 | <pre>{#syntax#}errdefer{#endsyntax#}</pre> |
| 11931 | 11958 | </th> |
| 11932 | 11959 | <td> |
| 11933 | | {#syntax#}errdefer{#endsyntax#} will execute an expression when control flow leaves the current block if the function returns an error. |
| 11960 | {#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. |
| 11934 | 11961 | <ul> |
| 11935 | 11962 | <li>See also {#link|errdefer#}</li> |
| 11936 | 11963 | </ul> |