On Sunday, 28 May 2017 at 20:06:42 UTC, piotrklos wrote:
I need to perform an action, in multiple separate functions, if
scope exits with an exception. The trouble is I don't want to
litter my code with scope(failure) everywhere. I already create
an instance of a struct at each location, with the sole purpose
of doing things at the end of scope.
So my code looks like:
function1()
{
RAIIType transactionHandler;
scope(failure) action;
//code
}
function2()
{
RAIIType transactionHandler;
scope(failure) action;
//code
}
function3()
{
RAIIType transactionHandler;
scope(failure) action;
//code
}
etc.
Ideally I would put the statement from scope(failure) in the
struct's destructor and delete the scope(failure) statements.
I would need something like c++'s std::uncaught_exceptions() to
check if an exception is in flight.
Is there something like this in D?
PS I think that we have here a more general problem, because
dlang is missing a feature for composition of scope(...)
statements.
Hard to do that way, only mixins come to mind.
However, if you want to do the same thing anywhere the failure
happens, most likely you want to do that at where you catch the
exception.
Another less likely, but possible, way is to have the struct
destructor to do the scope(exit) part only if it gets destroyed
in some certain state. For example, if the transaction receiver
is null.