throw Exception with custom message in nogc code
HubCool via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 4 23:25:28 PDT 2016
On Sunday, 5 June 2016 at 00:05:15 UTC, poliklosio wrote:
> I need to throw some exceptions in my code, but I don't want to
> ever care about the garbage collector.
>
> I have seen some solutions to throwing exceptions in nogc code,
> but only toy examples, like
> https://p0nce.github.io/d-idioms/#Throwing-despite-@nogc
>
> The solution sort of works, but doesn't show how to pass a
> custom string to the exception, and the text says "This trick
> is a dirty Proof Of Concept. Just never do it.".
> Is there a solution?
You can also "make!TheExceptionType(Mallocator.instance,
message)" And you stores them in a fixed length stack. On program
termination you free them.
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);
}
+--------------------------------------------------+
More information about the Digitalmars-d-learn
mailing list