当您丢弃并未处理std::runtime_error
时,终端自动打印what()
的结果,使调试变得更容易。例如:如何在抛出未处理的自定义异常之后调用what()?
#include <iostream>
int main()
{
throw std::runtime_error("This is an error message.\n");
}
控制台输出:
这个类派生自定义异常类表现出同样的行为,从头开始做的异常类不这样做,默认情况下。
但我想创建的异常类不能从std::runtime_error
派生。而为了调试目的,what()
仍然应该在程序崩溃后打印 - 但我不知道该怎么做,无论如何!有人能帮助我吗?
目前,它看起来像这样:
#include <iostream>
struct Custom_Exception
{
std::string Msg;
Custom_Exception(std::string Error_Msg) noexcept
{
Msg=Error_Msg;
}
std::string what() noexcept
{
return Msg;
}
};
int main()
{
throw Custom_Exception("This is an error message.\n");
}
控制台输出:
terminate called after throwing an instance of 'Custom_Exception'
错误消息没有what():
...把一个std::cout<<Msg;
进入析构函数并没有帮助。
请帮我提一下您的建议!谢谢。
“但我想创建的异常类不能从std :: runtime_error派生。” - 为什么不? –
在主体中捕获你的异常,并做他们想要的。我不会依赖运行时为你做这件事。 –
@NeilButterworth它迫使我使用某些数据类型或每次都将它们转换,它阻止了我创建一个我想用于我自己的项目的泛型异常类,我想知道如何添加此功能以便好奇心。我只是不喜欢这样。否则,我可以只使用std :: runtime_error本身...但我想通过自定义异常类,因为它可以确定的东西std :: runtime_error不能。 – Thynome