digitalmars.D - Specification of executing order of multiple scope(s)
- An Pham (29/29) May 31 2023 Should the scope failure to be executed before exit regardless of
- vit (30/59) May 31 2023 No, scopes are rewritten with compiler to something like this:
- Steven Schveighoffer (8/44) Jun 01 2023 From the [D
- bauss (3/32) Jun 02 2023 Just move the exit scope guard before failure and it will do what
Should the scope failure to be executed before exit regardless of the code order? import std.exception, std.stdio; void test() { writeln("test"); scope (failure) { writeln("failure"); } scope (exit) { writeln("exit"); } throw new Exception("exception"); } void main() { try { test(); } catch (Exception e) writeln(e.msg); } Output test exit failure exception
May 31 2023
On Wednesday, 31 May 2023 at 15:52:08 UTC, An Pham wrote:Should the scope failure to be executed before exit regardless of the code order? import std.exception, std.stdio; void test() { writeln("test"); scope (failure) { writeln("failure"); } scope (exit) { writeln("exit"); } throw new Exception("exception"); } void main() { try { test(); } catch (Exception e) writeln(e.msg); } Output test exit failure exceptionNo, scopes are rewritten with compiler to something like this: ``` void test() { writeln("test"); try{ try{ throw new Exception("exception"); } finally{ writeln("exit"); } } catch(Exception ex){ writeln("failure"); throw ex; } } void main() { try { test(); } catch (Exception e) writeln(e.msg); } ```
May 31 2023
On 5/31/23 11:52 AM, An Pham wrote:Should the scope failure to be executed before exit regardless of the code order? import std.exception, std.stdio; void test() { writeln("test"); scope (failure) { writeln("failure"); } scope (exit) { writeln("exit"); } throw new Exception("exception"); } void main() { try { test(); } catch (Exception e) writeln(e.msg); } Output test exit failure exceptionFrom the [D spec](https://dlang.org/spec/statement.html#scope-guard-statement): ``` If there are multiple ScopeGuardStatements in a scope, they will be executed in the reverse lexical order in which they appear. ``` -Steve
Jun 01 2023
On Wednesday, 31 May 2023 at 15:52:08 UTC, An Pham wrote:Should the scope failure to be executed before exit regardless of the code order? import std.exception, std.stdio; void test() { writeln("test"); scope (failure) { writeln("failure"); } scope (exit) { writeln("exit"); } throw new Exception("exception"); } void main() { try { test(); } catch (Exception e) writeln(e.msg); } Output test exit failure exceptionJust move the exit scope guard before failure and it will do what you want.
Jun 02 2023