Const static variables inside exception class

Dec 30, 2009 at 11:58am
Good morning.
I want to make an exception class with static const error codes inside. Like:
1
2
3
4
5
6
7
8
9
10
11
12
class exc_class
{
public:
  static const int error1=1;
  static const int error2=2;
  .
  .
  .
  exc_class(int error): errorCode(error){}
private: int errorCode;
};
  


And use it like:
throw exc_class(exc_class.error1);

It doesn't works for me. What I'm missing here?
Dec 30, 2009 at 12:56pm
You need the :: operator for static members:
exc_class::error1
Dec 30, 2009 at 4:28pm
Perhaps an enumeration would be a little more fitting for this specific scenario.
Dec 30, 2009 at 4:50pm
Personally, whenever I am tempted to do something like this, I prefer separate exception subclasses for each error type.

1
2
3
4
5
6
7
8
9
10
11
struct MyBaseException : public std::runtime_error
{
   MyBaseException(const std::string& msg) : std::runtime_error(msg.c_str()) {}
};

struct Error1 : public MyBaseException
{
  Error1() : MyBaseException("Error 1 message") {}
};

...


That way I can be as specific or general as I want with throw/catch.

And I find it a good practice to make every exception is a subclass of std::exception. That way every exception thrown follows, at a minimum, the semantics defined for std::exception. GCC, for example, can actually do something useful (print the exception type and message) with an uncaught exception in such cases.
Dec 30, 2009 at 9:54pm
Thanks for you feedbacks. Bazzy, you are right. I'll consider your advices in future, but this specific work is more on data structures and complexity.
Topic archived. No new replies allowed.