I can has @nogc and throw Exceptions?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 13 11:13:02 PST 2015


On 2/13/15 2:03 PM, Jonathan Marler wrote:
> This question comes from wanting to be able to throw an exception in
> code that is @nogc.
>
> I don't know if it's possible but I'd like to be able to throw an
> exception without allocating memory for the garbage collector? You can
> do it in C++ so I think you should be able to in D.  One idea I had was
> to allocate the memory for the Exception beforehand and create the
> Exception class with the pre-allocated memory.  I came up with the
> following code:
>
> T construct(T,A...)(void* buffer, A args)
> {
>    return (cast(T)buffer).__ctor(args);
> }
>
> Now to test it:
>
> void main()
> {
>    ubyte[ __traits(classInstanceSize, Exception)] exceptionBuffer;
>    throw construct!(Exception)(exceptionBuffer.ptr, "My Exception
> Allocated on the STACK!");
> }
>
> I got an assertion error. I'm not sure why, but when I print out the
> contents of the buffer of my stack exception it differs from an
> exception created for the garbage collector with "new".  It looks like
> it has some accounting information embedded in the class instance. I
> figured as much but I didn't think the code that performs the "throw"
> would be dependent on this.
>
> Also, this doesn't look like a very safe option because the initial
> values for the class members don't get set using this "construct" template.
>
> If anyone has any other ideas or a way to fix mine let me know, thanks.

You need to actually allocate the memory on the heap. Your data lives on 
the stack frame of main, which goes away as soon as main exits, and your 
exception is caught outside main.

-Steve


More information about the Digitalmars-d-learn mailing list