I have a class hierarchy, and each class in it has an exception class, derived in a parallel hierarchy, thus...
class Base
{
};
class Derived : public Base
{
};
From the OO standpoint, it is not reasonable. Since you say that DerivedException
is-a BaseException
, its possible reasons must be a subset of that of BaseException
, not a superset. Otherwise you ultimately break the Liskov Substitution Principle.
Moreover, since C++ enums are not classes, you can't extend or inherit them. You can define additional reasons in a separate enum within DerivedException
, but then ultimately you bump into the same problem described above:
class DerivedException : public BaseException
{
enum {
SOME_OTHER_REASON = THAT_REASON + 256, // allow extensions in the base enum
AND_ANOTHER_REASON
};
...
};
...
try {
...
} catch (BaseException& ex) {
if (ex.getReason() == BaseException::THIS_REASON)
...
else if (ex.getReason() == BaseException::THAT_REASON)
...
else if (ex.getReason() == ??? what to test for here ???)
...
}
What you can do instead is define a separate exception subclass for each distinct reason. Then you can handle them polymorphically (if needed). This is the approach of the standard C++ library as well as other class libraries. Thus you adhere to the conventions, which makes your code easier to understand.