Reputation: 169
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!
Upvotes: 3
Views: 2693
Reputation:
You need to actually catch your exception:
try
{
throw stack_full_error("Stack is full!");
} catch(stack_full_error& ex)
{
std::cout << ex.what();
}
Upvotes: 3