Custom default exception handler?

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Mon Feb 10 21:09:04 PST 2014


On 2/10/2014 10:57 PM, Adam D. Ruppe wrote:
> On Tuesday, 11 February 2014 at 03:53:05 UTC, Nick Sabalausky wrote:
>> I don't suppose there's a way to change the default exception handler
>> without using a modified druntime
>
> I'm pretty sure there used to be, but not anymore looking at the source.
> The d_run_main function has a hardcoded catch block.
>
> Why do you need to change the default though? Can't you just wrap your
> own main function in a big try/catch block?

I don't strictly *need* to. But if you're curious, here's the story:

I like to use a little custom exception (Fail) in shell script-like 
stuff to bail out and exit with a given error message in an 
exception-safe way. This is for expected failure conditions, not 
internal errors (so for example: "copy src.txt" -> "Error, no 
destination given!" or "File src.txt doesn't exist!", etc), so the stack 
trace is unnecessary noise and omitted. Only the message is printed, 
maybe with a common prefix like "mytool: ERROR: ...".

This is arguably a slight abuse of the exception system, but in 
script-like stuff the exception performance doesn't really matter, and I 
find it does greatly simply the error logic of D-based scripts. Helps 
keep simple scripts simple.

I'm sticking this Fail stuff into a little utility lib for simple 
script-like programs, and so, if possible, I'd *like* to instruct users 
to just do this:

void main() {
     installFailHandler();
     ...
}

instead of all this boilerplate:

int main() {
     try {
         ...user code...
     }
     catch(Fail e) {
         writeln(e.msg);
         return 1;
     }

     return 0;
}

I'm sure I could also do something like this, but it's rather ugly:

int main() {
     mixin(handleFail!(() => {
         ...user code...
     }));
}

So not a real big deal, but it'd be nice if I could swing it.



More information about the Digitalmars-d-learn mailing list