scope(exit) and scope(failure) on Errors

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 25 07:24:25 PDT 2016


On 4/25/16 4:42 AM, Shachar Shemesh wrote:
> There is a problem with scope(exit) and scope(failure) running when
> Error types exceptions are thrown. It throws the program into code paths
> that are really not healthy.
>
> Imagine, for example, code handling linked lists. We do manipulations on
> linked lists, and put a scope(exit) that clears stuff up.
>
> Now imagine that somewhere inside, we have an assert that makes sure
> that everything is still in order. If it's not, then an AsserError is
> thrown, which derive from Error. The scope(exit) runs, but since things
> are not where they should be (hence the assert), we segfault. All the
> useful stuff that the assert was supposed to provide us is now gone,
> replaced by cleanup code that had no business running under those
> circumstances.
>
> Even when not harmful, this is, often, useless. Even if the cleanup
> proceeds correctly, what is the sense of cleaning up when the program is
> in serious trouble?
>
> The above is not categorically always true. In Weka, for example, we are
> using exceptions derived from Error to force all fibers of a certain
> logical component to exit. It is useful that these exceptions are not
> caught. In those cases, there are some types of cleanups that we do want
> to take place, but not others.
>
> Some way to control this would be appreciated.

If your scope(exit) code can only run when things are intact, why not 
use scope(success) instead?

It's coarse though, no difference between exceptions or errors. But it 
may be a good stop-gap fix.

A nice thing may be allowing to check on the inflight exception (or lack 
thereof) on scope(exit) and scope(failure).

Note that scope guards I think are actually implemented via try catch 
statements, you could try just doing those instead (though obviously, it 
doesn't read as nicely).

-Steve


More information about the Digitalmars-d mailing list