The Right Approach to Exceptions
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon Feb 20 13:17:47 PST 2012
On 2/20/12 3:06 PM, Juan Manuel Cabo wrote:
> I like one golden rule that I have:
>
> "You should only create a new exception type, if it makes sense to write
> a catch(MyNewShinyType ex){} "
The problem with this is that anyone may come with an example created on
the spot where they would, actually, want to catch a specific exception.
It's very hard to make non-existential proofs.
> other reasons for creating a new exception class I don't consider them valid
> (but that's just me!).
> This is because, exception types (in my head) are only a way to distinguish
> whether to select them or let them go when I write a catch(), and to
> help the catch recover. Now, if I can't distinguish the *what* of the error,
> I cannot recover well. The *cause* of the error goes inside the exception
> object, not encoded in the type. Other details of the error go inside of
> the exception object, not encoded in the type name.
>
> So all I care about is the *what* of the error, so that it will fall in
> the correct catch statement. Other criteria obscures that.
>
> The Variant[string] helps keep the hierarchy clean. The hierachy should
> tell the *what* of the error so that I can pick one when writing a catch block.
Don't forget that you always have the option of creating a type on the spot.
void fun()
{
if (oops)
{
class MyException : Exception
{
string reasonForOops;
...
}
throw new MyException; // RTTI will find reasonForOops
}
}
But after seeing a variety of pros and cons, I tend to agree that the
Variant[string] is more attractive.
Andrei
More information about the Digitalmars-d
mailing list