Specification of executing order of multiple scope(s)

vit vit at vit.vit
Thu Jun 1 05:46:08 UTC 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
> exception

No, 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);
	}
```


More information about the Digitalmars-d mailing list