Reputation: 4767
I tried to figure out how to implement my own base class for C++ exceptions which allow adding an error specific text string. I see no possibility for the std::c++ exceptions to change the error text, even not in C++11: http://www.cplusplus.com/reference/exception/exception/. I also want to derive more specific exceptions from my Exception-base class. I read a lot of articles but I am still unsure whether my following implementation covers all important aspects.
class Exception : public std::exception {
public:
Exception(const char* message) : m(message) {
}
virtual ~Exception() throw() {
}
virtual const char* what() const throw() {
return m.c_str();
}
protected:
std::string m;
private:
Exception();
};
Is this implementation fine?
Upvotes: 1
Views: 2046
Reputation: 21040
If you derive from runtime_error
(and your compiler supports inheriting constructors) you can condense your class to
struct Exception : public std::runtime_error
{
using runtime_error::runtime_error;
};
throw()
: Exception specifications are deprecated as of C++11, use noexcept
instead.
Upvotes: 3