scope guards

Idan Arye via Digitalmars-d digitalmars-d at puremagic.com
Sat Aug 9 04:51:05 PDT 2014


On Saturday, 9 August 2014 at 00:17:07 UTC, Jonathan M Davis 
wrote:
> On Friday, 8 August 2014 at 12:22:49 UTC, Idan Arye wrote:
>> On Friday, 8 August 2014 at 08:37:37 UTC, Messenger wrote:
>>> On Friday, 8 August 2014 at 00:27:21 UTC, Jonathan M Davis 
>>> wrote:
>>>> On Thursday, 7 August 2014 at 20:59:45 UTC, Messenger wrote:
>>>>> On Thursday, 7 August 2014 at 20:54:02 UTC, Jonathan M 
>>>>> Davis wrote:
>>>>>> I'd say that if you're trying to use scope in any 
>>>>>> situation where you'd try and handle an exception, then 
>>>>>> you're using it wrong.
>>>>>
>>>>> But it's super convenient.
>>>>
>>>> It fundamentally doesn't work to handle an exception with a 
>>>> scope guard. They rethrow the exception.
>>>
>>> void fun() {
>>>   scope(failure) return;
>>>   throw new Exception(__FUNCTION__);
>>> }
>>>
>>> void main() {
>>>   import std.exception;
>>>   assertNotThrown(fun());
>>> }
>>
>> Initially I thought this was a bug, but this seems intended 
>> since it doesn't work with `scope(exit)` - it yields the 
>> compiler error "Error: return statements cannot be in finally, 
>> scope(exit) or scope(success) bodies".
>
> I suspect that it says that because someone complained about 
> the error talking about finally when they had used scope(exit) 
> and not finally. The fact that scope statements get lower to 
> try-catch-finally blocks allow for a few screwy things that 
> were not intended. Whether those things will be left in or made 
> illegal at this point is another matter, but I'm sure that it 
> was never the intention that anyone be allowed to return from 
> any kind of scope statement or do anything else which would 
> cause the exception to not be rethrown.
>
> - Jonathan M Davis

If that was the case, the error would have said it's illegal to 
throw from "finally or scope bodies". The fact that it 
specifically specifies `scope(exit)` and `scope(success)` and 
leave out `scope(failure)` means that whoever wrote that error 
message made a conscious decision that it's OK to return in 
`scope(failure)`.


More information about the Digitalmars-d mailing list