The Right Approach to Exceptions
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Sun Feb 19 09:19:42 PST 2012
On 2/19/12 4:30 AM, Juan Manuel Cabo wrote:
> Now, expanding on the hierarchy: I said that it makes no sense to
> subclass UnrecoverableExceptions. Recoverable exceptions on the other
> hand, need to be subclassed _with_the_catch_on_your_mind_. You are
> passing info from the throw site to the catch site. The catch block is
> the interpreter of the info, the observer. You are communicating
> something to the catch block.
>
> So please, do not create a new types if there is no value in writing a
> catch that only cathes that exception and that can recover from that
> exception. Otherwise, use an existing type.
I think this is a very sensible point. I wonder to what extent it
clashes with a simple idea that just occurred to me. It would be very
easy to define a hierarchy as follows:
class ModuleException(string theModule) :
PackageException(packageOf(theModule))
{
...
}
Then any module could issue
throw new ModuleException!(.stringof);
That way the exception hierarchy would parallel the module hierarchy. (A
module is free to define more specific exception inheriting
ModuleException!(.stringof)).
The catcher would catch things like ModuleException!"acme.text.io" and such.
In that approach, all exceptions thrown from Phobos would inherit
PackageException!"std" and all exceptions thrown from std.getopt would
be (or inherit) ModuleException!"std.getopt".
This would save a lot on the boilerplate while still keeping open the
option of defining fine-grained hierarchies. Any thoughts, please chime.
Andrei
More information about the Digitalmars-d
mailing list