Proposal 2: Exceptions and @nogc

Jonathan Marler via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 10 13:10:38 PDT 2017


On Monday, 10 April 2017 at 13:00:52 UTC, Jacob Carlborg wrote:
> On 2017-04-09 05:26, Walter Bright wrote:
>> My previous version did not survive implementation. Here's the 
>> revised
>> version. I have submitted it as a DIP, and there's a trial
>> implementation up:
>
> What exactly does the user have to do to use throw a RC 
> exception instead of a GC exception?

The compiler makes it refcounted if and only if you are 
"throwing" and "newing" in the same statment, i.e.

     throw new E(); // refcounted

I can see 2 reasons for this:

1) Because you are throwing the new object, your code has no 
opportunity to misuse the "ref-counted" object.  The exception 
handler takes over immediately so you have no opportunity to leak 
the object.  The only place that can reference it will be in the 
catch chain which will have the cleanup code auto generated by 
the compiler.

2) No syntax change! Because this isn't a general solution for 
ref-counted objects, a "no-syntax" feature allows the solution to 
be rolled out with no library changes which means we aren't 
investing a lot of unnecessary turmoil in case a new general 
solution comes out.

After thinking about the proposal the whole thing seems to be 
quite clever.  I think it takes some time to wrap your mind 
around why though.

If you want to force a GC exception (though I'm not sure why you 
would), you could do this:

     auto e = new E(); // GC
     throw e;

I like the discussion about this proposal and I think Walter has 
addressed the big concerns.  Everyone agrees this only solves a 
specific problem, but it's a BIG problem and since it doesn't 
change the syntax it can easily be swapped out for any future 
general solutions.

Also I think requiring a copy to escape an exception is fine, 
anyone who doesn't think so doesn't understand the overhead of an 
exception. But if it's really an issue for people (people who 
want to force GC exceptions for some reason), you could add a new 
method to the Exception object that gives you an escapable 
reference.

Exception getEscapableReference();

A refcounted exception would create a copy, whereas a GC 
exception would just return itself.


More information about the Digitalmars-d mailing list