Hi I have a c++ assignment in which I need to create my own exceptions. My exception class has to inherit from the std::exception and 2 other classes need to derive from that one. The way I have it right now it actually compiles and works pretty much ok. But when the exception is thrown I get e.g.: terminate called after throwing an instance of 'stack_full_error' what(): The stack is full! Aborted (core dumped)
I am very confused about this matter and unfortunately I could not find much help on the web or in my books. My header is something like the following:
class stack_error : public std::exception
{
public:
virtual const char* what() const throw();
stack_error(string const& m) throw(); //noexpect;
~stack_error() throw();
string message;
private:
};
class stack_full_error : public stack_error
{
public:
stack_full_error(string const& m) throw();
~stack_full_error() throw();
virtual const char* what() const throw();
};
class stack_empty_error : public stack_error
{
public:
stack_empty_error(string const& m) throw();
~stack_empty_error() throw();
virtual const char* what() const throw();
};
and my implementation is:
stack_error::stack_error(string const& m) throw()
: exception(), message(m)
{
}
stack_error::~stack_error() throw()
{
}
const char* stack_error::what() const throw()
{
return message.c_str();
}
stack_full_error::stack_full_error(string const& m) throw()
: stack_error(m)
{
}
stack_full_error::~stack_full_error() throw()
{
}
const char* stack_full_error::what() const throw()
{
return message.c_str();
}
stack_empty_error::stack_empty_error(string const& m) throw()
: stack_error(m)
{
}
stack_empty_error::~stack_empty_error() throw()
{
}
const char* stack_empty_error::what() const throw()
{
return message.c_str();
}
any help would be greatly appreciated!
throw()specification removed because each one of them actually can throw an exception! I don't think there is a reason to make thestd::stringapublicmember, either, and it is surely sufficient to overridewhat()just in the base class. Can you show the code where you actually catch the exception?virtualinheritance when creating your own exception types. Also, ifstack_errorinherits fromruntime_errorinstead ofexceptionyou won't need thestringmember variable.