Skip to content

Instantly share code, notes, and snippets.

@DmitryOlshansky
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitryOlshansky/59ec5953874bc1985ac5 to your computer and use it in GitHub Desktop.
Save DmitryOlshansky/59ec5953874bc1985ac5 to your computer and use it in GitHub Desktop.
writeln/writefln style exceptions
/// $(D write)-style construction of exceptions, optionally with given super type.
auto exception(Base=Exception, string file = __FILE__,
size_t line = __LINE__, Args...)(Args args)
{
return exceptionfImpl!Base(null, args, file, line);
}
/// $(D writef)-style construction of exceptions, optionally with given super type.
auto exceptionf(Base=Exception, string file = __FILE__,
size_t line = __LINE__, Args...)(string fmt, Args args)
{
return exceptionfImpl!Base(fmt, args, file, line);
}
auto exceptionfImpl(Base, Args...)(string fmt, Args args,
string file, size_t line)
{
static class Ex : Base {
Args args;
this(string fmt, Args args, string file, size_t line)
{
super(fmt, file, line);
this.args = args;
}
override void toString(scope void delegate(in char[]) sink) const
{
import std.format : formattedWrite;
formattedWrite(sink, "%s@%s(%d):",
Base.stringof, file, line);
if(msg.ptr) // msg is format string
{
formattedWrite(sink, msg, args);
}
else
{
foreach(arg; args)
formattedWrite(sink, "%s", arg);
}
}
};
return new Ex(fmt, args, file, line);
}
void main()
{
import std.stdio;
//throw exception("bc", 10);
//throw exception("bc", 10);
throw exceptionf!Throwable("%s__%s", 2.14, 8);
//writeln(exceptionf("%s__%s", 2.14, 8));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment