throw Exception with custom message in nogc code
poliklosio via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 5 03:37:49 PDT 2016
On Sunday, 5 June 2016 at 06:25:28 UTC, HubCool wrote:
> (...)
> But I'd say that the leak doesn't matter. Either the soft has a
> very small problem that happens once eventually, otherwise it's
> a big bug and new exceptions will come so often that the
> program has to be killed immediatly.
>
> +--------------------------------------------------+
> auto leakAnoGcException(T, A...)(A a) @nogc
> if (is(T: Exception))
> {
> import std.experimental.allocator.mallocator;
> import std.experimental.allocator;
> return make!T(Mallocator.instance, a);
> // eventually stores them ona stack that you can free in
> static ~this()
> }
>
> void main() @nogc
> {
> bool ouch;
> class MyException: Exception {this(string m) @nogc
> {super(m);}}
> try throw leakAnoGcException!MyException("ouch");
> catch (Exception e) {ouch = true;/*can dispose here
> too...*/}
> assert(ouch);
> }
> +--------------------------------------------------+
I like your solution, as it doesn't force to allocate exception
objects statically, which is a step forward.
On the other hand I don't think that the leak doesn't matter.
This would only be the case if one could guarantee that only a
small, constant number of exceptions is thrown during program
execution. This is not generally the case. Also, exceptions are
not necessarily for bugs. There may be used sometimes for bug
handling when other things like static typing and assertions are
not enough, but bug handling is not the core reason for havi ng
exceptions in languages.
Exceptions is a control flow construct for use in events which
occur rarely (relative to normal execution of surrounding code)
and require jumping many levels up the call stack. That's all
there is to them. Its not some philosophical concept that depends
on the definition of errors or bugs.
Can you elaborate on how to dispose the exception?
I'm partilularly interested in the code you would write in place
of the /*can dispose here too...*/ comment.
More information about the Digitalmars-d-learn
mailing list