gpt4 book ai didi

C++ 通过继承 std::exception 创建新的异常

转载 作者:太空狗 更新时间:2023-10-29 21:22:14 25 4
gpt4 key购买 nike

您好,我有一个 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();
}

如有任何帮助,我们将不胜感激!

最佳答案

您需要实际捕获您的异常:

try
{
throw stack_full_error("Stack is full!");
} catch(stack_full_error& ex)
{
std::cout << ex.what();
}

关于C++ 通过继承 std::exception 创建新的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com