C++ Creating custom exception class
The following code segment demonstrates how to create a C++ custom exception class. The important thing to note is that the base exception:what() function has the following signature:
const char * what() const throw()
Thus to override the base exception::what function, the custom exception class must declare the function signature properly otherwise, it becomes a case of function name hidding as explained in one of the previous C++ articles.
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() const throw() { return msg.c_str(); }
private:
string msg;
};
int main()
{
try
{
throw Exception();
}
catch(exception& e)
{
cout << e.what() << endl;
}
return 0;
}
const char * what() const throw()
Thus to override the base exception::what function, the custom exception class must declare the function signature properly otherwise, it becomes a case of function name hidding as explained in one of the previous C++ articles.
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() const throw() { return msg.c_str(); }
private:
string msg;
};
int main()
{
try
{
throw Exception();
}
catch(exception& e)
{
cout << e.what() << endl;
}
return 0;
}
<< Home