throw Exception with custom message in nogc code
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 4 17:23:31 PDT 2016
On 06/04/2016 05:05 PM, 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?
Regardless of the sanity or the usefulness of the idiom, it's possible
to mutate the .msg property of the exception object:
import std.stdio;
class MyException : Exception {
this(string msg) {
super(msg);
}
void setMessage(string msg) @nogc {
super.msg = msg;
}
}
// Statically initialize an exception instance.
MyException g_Exception;
static this() {
g_Exception = new MyException("This message won't be helpful");
}
// Function that throws despite being @nogc
void nogcFunction() @nogc
{
g_Exception.setMessage("Helpful message");
throw g_Exception;
}
void main() {
try
{
nogcFunction();
}
catch(const(Exception) e)
{
// Message, file and line number won't be given though
import std.stdio;
writefln("Received an exception: %s", e.msg);
}
}
Outputs
Received an exception: Helpful message
Ali
More information about the Digitalmars-d-learn
mailing list