【发布时间】:2014-01-25 20:33:48
【问题描述】:
您好,我有一个 c++ 任务,我需要在其中创建自己的异常。我的异常类必须从 std::exception 继承,其他 2 个类需要从该类派生。我现在拥有它的方式实际上可以编译并且工作得很好。但是当抛出异常时,我得到例如: 在抛出“stack_full_error”的实例后调用终止 what():堆栈已满! 中止(核心转储)
我对这件事感到非常困惑,不幸的是我在网上或我的书中找不到太多帮助。我的标题是这样的:
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();
};
我的实现是:
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();
}
任何帮助将不胜感激!
【问题讨论】:
-
你发现异常了吗?
-
您发布的代码看起来大部分都在工作:构造函数都应该删除
throw()规范,因为它们中的每一个实际上可以抛出异常!我也不认为有理由将std::string设为public成员,而且仅在基类中覆盖what()肯定就足够了。你能展示你实际捕获异常的代码吗? -
Please consider using
virtualinheritance 创建自己的异常类型时。此外,如果stack_error继承自runtime_error而不是exception,则您将不需要string成员变量。 -
非常感谢。看来我忘记改变我的“catch”了,我还在寻找一个 std::out_of_range。
标签: c++ class exception c++11 exception-handling