Reputation: 6076
So I am a little confused, I have been looking around trying to determine an appropriate way of inheriting from std::exception for my own type. Now according to cplusplus.com (and i know this isn't necessarily the standard, thats why I'm asking), std::exception is a base class with no members. However, after looking at my implementation of the standard library (VS 2005), the class std::exception is quite clearly defined with two member variables:
class _CRTIMP_PURE exception
{ // base of all library exceptions
...
private:
const char *_m_what;
int _m_doFree;
};
Now is this standard to have these members included within the base class std::exception, my understanding was that it isn't. My reason for asking is that my derived exception class really only needs a single string for its information, thus this implementation would work fine. However, I'm worried that this is non-standard, and as such I might be better off inheriting from std::exception and adding the appropriate members + copy/assignment code myself.
Upvotes: 2
Views: 1268
Reputation: 264709
I would look at the other standard exceptions aswell.
std::exception may be the base class but other standard exceptions provide some other features.
I usually derive from std::runtime_error
Upvotes: 1
Reputation: 67847
To make your own exception class, you want to overload the following function:
virtual const char* what() const throw()
If you look at the Visual Studio implementation, exception
uses malloc
to allocate memory to store the character string. If that memory isn't available, _m_what
is set to a predefined string.
_m_doFree
is a flag that stores whether free
needs to be called on this memory.
Upvotes: 2
Reputation: 59623
The std::exception
class is defined as:
namespace std {
class exception {
public:
exception() throw();
exception(const exception&) throw();
exception& operator=(const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
};
}
That is the contract that you have to live up to when it comes to substitutability. The Standard defines the specifics of each member. The only one that usually requires consideration is that what()
returns a "null-terminated multi-byte string, suitable for display as a wstring
". The other part is obeying and ensuring the throw()
contract.
Upvotes: 6