Alex Rivera | Logout

Extending enum in derived classes

Asked 2010-09-07T14:14:57.213
16

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
{
};

class BaseException : public std::exception
{
   enum {THIS_REASON, THAT_REASON};
};

class DerivedException : public BaseException
{
    // er...what?
};

I would like, in the DerivedException class, to extend the enumeration type to include a new value THE_OTHER_REASON, so that the DerivedException class could hold any of the three values.

First of all, ought I to want to do this? Does it seem a reasonable practice? If so, how do I go about it? If not, what alternatives would you recommend?

EDIT: A possible duplicate has been suggested here, but the suggested solutions are different because that question is for C# and this for C++.

Edit
Report

2 Answers

11

To me, it seems more reasonable to have an exception class for each exception reason. When handling an exception, it is usually not interesting to know which class threw the exception, but for what reason the exception was thrown.

If you want to keep your design: C++ does not allow you to extend an existing enum, but you can create a new enum that starts where a previous one left off:

class BaseException : public std::exception
{
   enum {THIS_REASON, THAT_REASON, END_OF_BASE_REASONS };
};

class DerivedException : public BaseException
{
   enum {OTHER_REASON = BaseException::END_OF_BASE_REASONS };
};
answered 2010-09-07T14:22:28.310
2

You could do this, since you use unnamed enums. I suppose you use integer type to store the reason of the exception.

class DerivedException : public BaseException
{
    enum { YET_ANOTHER_REASON = THAT_REASON + 1, EVEN_MORE_REASON};
};

I wouldn't encode reasons as codes. I would prefer specialized exception classes, so I can catch only the exception types that I can handle at one moment.

answered 2010-09-07T14:19:30.193

Your Answer