scope(failure) compiles but is not called if it inside of block

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 31 22:45:05 UTC 2019


On Thursday, January 31, 2019 1:05:31 PM MST Denis Feklushkin via 
Digitalmars-d wrote:
> code: https://run.dlang.io/is/GgQjfV
>
> /++ dub.sdl:
> name "ttest"
> description "test"
> +/
>
> import std.stdio;
> import std.exception;
>
> void main()
> {
>      scope(failure) writeln("1");
>
>      {
>          scope(failure) writeln("2"); // compiles but is not
> called for some reason
>      }
>
>      scope(failure) writeln("3");
>
>      enforce(false); // throws exception
> }
>
>
> Outpupt:
> Running ./ttest
> 3
> 1
> object.Exception at bitop_bt.d(19): Enforcement failed

Note that the keyword is _scope_. scope(failure) will run if an exception is
thrown after the scope statement within the current scope. Braces add a new
scope.

{
    scope(failure) writeln("2");
}

is essentially equivalent to

{
    try
    {
    }
    catch(Exception e)
    {
        writeln("2");
        throw e;
    }
}

There is no code within the try block which could possibly throw, so the
catch block will never run. Your entire function is essentially the same as

void main()
{
    try
    {
        {
            try
            {
            }
            catch(Exception e)
            {
                writeln("2"); // compiles but is not called for some reason
                throw e;
            }
        }

        try
        {
            enforce(false); // throws exception
        }
        catch(Exception e)
        {
            writeln("3");
            throw e;
        }

    }
    catch(Exception e)
    {
        writeln("1");
        throw e;
    }
}

BTW, questions about D really belong in D.Learn. The main newsgroup is
intended for general discussions about D, not for asking questions about it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list