On Tuesday, 17 February 2015 at 13:32:40 UTC, Matthias Bentrup
wrote:
Maybe it is possible to have a separate ScopedThrowable
exception class.
Those exceptions would be allocated on the stack and would be
allowed to carry references to local/scoped data, but they live
only for the duration of the corresponding exception handler.
The compiler should check that the exception and its payload
don't escape the catch block, and of course the exception
handler has to run before the stack unwinding is done.
The whole point is of course that ScopedThrowables could be
thrown from @nogc functions.
In response to allocating an exception on the stack...It depends
on when you allocate the exception. If the "catcher" of the
exception allocates it on the stack, then you are fine so long as
you have a way to pass a reference to it to any children
functions, however, if the thrower allocates it on the stack then
the memory will be released when the exception gets thrown. It
may make sense in some cases for the "catcher" to allocate the
exception but I don't think that would be the norm.
The reason you can't keep the "thrower's" stack memory around for
the exception handler is because the exception handler may need
that memory. Once the exception is thrown the stack is unwound
to the function that has the exception handler so all the memory
gets released. In most cases the exception handler probably won't
mess up the memory the exception is using, but that can't be
guaranteed.
As far as preventing the exception from escaping the catch
block...that's precisely what the scope keyword would ensure.
Exception myException;
try {
SomethingBad();
} catch(scope Exception e)
{
myException = e; // Nope. e is a scoped variable
// Note: if you needed the exception outside this
// block then you could copy the memory to another
// location.
}