scope + destructor with Exception parameter for RAII
Sean Kelly
sean at f4.ca
Wed Nov 29 06:12:26 PST 2006
Leandro Lucarella wrote:
> Sean Kelly escribió:
>> Leandro Lucarella wrote:
>>> What do you think of adding an optional parameter (exception) to the
>>> destructor, defaulting to null, to indicate the destructor was called
>>> then unwinding because an exception was thrown? Then you can almost
>>> forget about scope(exit/success/failure) and you have a RAII as
>>> complete as Python's 'with' statement.
>>
>> I don't like it, personally. It doesn't seem a good idea for a dtor
>> to alter its behavior based on whether an exception is in flight, and
>> exceptions should never be thrown from dtors anyway. Doing so makes
>> writing correct code far too complicated.
>
> Exceptions would not be thrown from the dtor, it just executes some code
> if it was executed during an unwinding because an exception was raised:
>
> scope Transaction t = new Transaction();
> throw Exception("ouch!");
>
> Here the Transaction.~this(Exception) is called, but there is no
> Exception throwing in the dtor.
So are you saying you want this feature to allow Transaction to decide
whether to roll-back or commit? I had assumed it was to determine
whether it was "safe" for Transaction's dtor to throw an exception itself.
> I don't see why writing correct code is that complicated. And how do you
> address the problem of repeating error handling code and the lack of
> encapsulation of scope(success/failure)?
The lack of encapsulation doesn't bother me much, though now I see what
you're getting at. I do think that having:
auto scope t = new Transaction();
scope(failure) t.rollback();
// commits if not rolled back on scope exit, alternately use
scope(success) t.commit();
actually aids readability a bit, at the expense of some extra code.
That said, I have considered adding a routine that the user can call to
determine whether an exception is in flight. Similar to the one in C++,
but without all the annoying shortcomings. It would mean setting a
thread-local flag or pointer in the internal exception handling code,
etc. I think this is a better approach than altering dtor syntax for
the same purpose, as it avoids language changes and doesn't lose any
usefulness in the process.
> Any other thoughts on this (the thread diverged a little from the
> original topic ;)?
See above :-)
Sean
More information about the Digitalmars-d
mailing list