Thread overview
Specification of executing order of multiple scope(s)
May 31, 2023
An Pham
Jun 01, 2023
vit
Jun 02, 2023
bauss
May 31, 2023

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

June 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
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);
	}
June 01, 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
exception

From the D spec:

If there are multiple ScopeGuardStatements in a scope, they will be executed in the reverse lexical order in which they appear.

-Steve

June 02, 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

Just move the exit scope guard before failure and it will do what you want.