I am writing some new code that will throw a custom exception – I want to include an error string and a status code. Which class should be exception derive from? std::exception? std::runtime_error? Any other ‘gotchas’ to worry about? I’m thinking of something like the following:
class MyException : public std::exception(?) { public: enum Status { ERROR_FOO, ERROR_BAR, ... }; MyException(const std::string& error, Status code) : error_(error), code_(code) { ... } virtual const char* what() const { return error_.c_str(); } Status code() const { return code_; } private: std::string error_; Status code_; };
Then in the code:
throw MyException('Ooops!', MyException::ERROR_BAR);
Boost has a great document on error and exception handling which talks about common gotchas and how to properly inherit from std::exception(s).