More exception classes into Phobos?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 23 13:48:24 PDT 2017


On Thursday, March 23, 2017 21:34:45 Jacob Carlborg via Digitalmars-d wrote:
> On 2017-03-23 20:47, Walter Bright wrote:
> > Thanks for expressing this better than I could have. Over time I've
> > found that standardized Exception types seem to become less and less
> > useful over just using "Exception" with an appropriate message.
>
> A plain Exception is completely useless, it can just as well be an
> assertion instead. Because it's not possible to extract any information
> from the exception (except for trying to parse the message which is a
> bad idea) resulting in not being able to act on a thrown exception.
> Which then results in it being pointless to catch the exception in the
> first place.
>
> I think it's a bad design that it's possible created instances of
> Exception, it should either be an abstract class or an interface.

There are plenty of cases where all you care about is that something went
wrong when calling a function and aren't going to do anything special
depending on what went wrong. You just handle it and move on. In other
cases, any exception of any kind means that you're done and exiting your
program, which _is_ similar to an assertion, but the key difference is that
assertions are for catching programming errors, not for reporting stuff like
bad user input or that the file you're trying to operate on doesn't exist
anymore. Regardless, having a generic exception type is useful.

Now, there are plenty of cases where specific exception types should be used
- particularly if you want to be able to have your program respond
differently depending on what went wrong - but for those to be effective,
they need to actually be specific, whereas most any exception type that one
might consider adding to std.exception is generic and thus in pretty much
the same boat as Exception. So, I see no point in general exceptions like
IOException. In those cases, you might as well just use Exception.

I frequently create specific exception types for libraries that I write or
for pieces of libraries, because then you know where the exception came
from (which can affect how you handle it), and if it's a specific type
related to specific functionality within a library, then catching it
specifically can really inform what exception handling code should be doing.

That being said, there are plenty of cases where I'm not sure that there's
much point in creating a new exception type. If it's not something that
someone is going to handle differently depending on its type, and all you
really care about reporting is that something went wrong, Exception is
perfect for that. And in cases like D scripts, it would be overkill to be
forced to create your own exception types, so it would really annoying if
you couldn't create Exceptions.

- Jonathan M Davis



More information about the Digitalmars-d mailing list