Exceptions in @nogc code

Matthias Bentrup via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 3 01:22:41 PDT 2017


On Saturday, 1 April 2017 at 13:34:58 UTC, Andrei Alexandrescu 
wrote:
> Walter and I discussed the following promising setup:
>
> Use "throw new scope Exception" from @nogc code. That will 
> cause the exception to be allocated in a special stack-like 
> region.
>
> If the catching code uses "catch (scope Exception obj)", then a 
> reference to the exception thus created will be passed to 
> catch. At the end of the catch block there's no outstanding 
> reference to "obj" so it will be freed. All @nogc code must use 
> this form of catch.
>
> If the catching code uses "catch (Exception obj)", the 
> exception is cloned on the gc heap and then freed.
>
> Finally, if an exception is thrown with "throw new Exception" 
> it can be caught with "catch (scope Exception obj)" by copying 
> the exception from the heap into the special region, and then 
> freeing the exception on the heap.
>
> Such a scheme preserves backward compatibility and leverages 
> the work done on "scope".
>
>
> Andrei

How would you deal with the Exception payload, e.g. the message 
string ? If I have to place it on the heap, I lose @nogc, if I 
place it in the local scope, it will be destroyed before the 
Exception handler is called and if I restrict the mechanism to 
fixed payloads, I could have used static Exception objects in the 
first place.

It may be possible to copy the message string from local scope to 
the special stack on throw, but in the general case the payload 
could be an arbitrary tree of Objects allocated on the heap or 
the stack, or even on the special exception stack itself.

A method I used to pass scope data up the stack is by using 
"thrower delegates", i.e. the @nogc throwing function doesn't 
directly throw an Exception, but it calls a delegate that is 
passed all the payloads as arguments and which throws a static 
Exception.

This thrower delegate is provided by the Exception catching 
function, and has the opportunity to read/copy the parts of the 
payload it is interested in before the stack is unwound.



More information about the Digitalmars-d mailing list