More exception classes into Phobos?

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 23 18:44:02 PDT 2017


On Friday, 24 March 2017 at 00:28:16 UTC, Walter Bright wrote:
> The string is what gets printed to the user like:
>
>    "your password has to have at least one upper case character 
> in it"
>
> In general, such is not deducible from the type/arguments.

Yes, of course they are. In the simplest case in D, we could do 
throw new ExceptionImpl!string instead of throw new 
Exception(string), then it is absolutely deducible from the type, 
since it is a part of the type by definition.

That also becomes catchable independently of other exceptions 
(have you ever done something like `catch(Exception e) if(e.msg 
!= "foo") throw e;`? I actually have literally done that with a 
crappy D library that threw an exception that I could recover 
from with a retry...), avoids any runtime allocation of the 
string, and is potentially easier to internationalize if you want 
to present it to the end user.

That's not how I'd literally do it, but it is something we CAN do 
in D (and would be an improvement from the status quo, without 
being a hassle of hierarchies).

> Exceptions are not for debugging the code (that's what Errors 
> are for), Exceptions are for informing the user that he did it 
> wrong.

All the more reason to actually make them as informative as 
possible (...and likely to cut out most the irrelevant stack 
trace). If the user is another programmer calling your function, 
they ought to be able to catch and inspect the exception in order 
to retry.

Moreover, informing the user wants to have as much info as 
possible. We've probably all been frustrated by in D by "Range 
violation" but it doesn't tell us what the value actually was. 
Attaching an int and sinking it into the error message ought to 
be trivial... and it IS, yet druntime doesn't do it. (and yes, I 
know that's an Error, not an Exception, but same reasoning 
applies)

I only care about the hierarchy insomuch as I intend to catch it 
without catching something else from the same block of code.


try {
     throw new RangeErrorImpl!(size_t, size_t, size_t)(x, 0, 
array.length);
} catch(RangeError e) {
     // this suddenly became a billion times more useful
     e.toString(sink); // RangeError, 10, 0, 8
}


More information about the Digitalmars-d mailing list