Const static variables inside exception class

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?
You need the :: operator for static members:
exc_class::error1
Perhaps an enumeration would be a little more fitting for this specific scenario.
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.
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.