【发布时间】:2017-02-27 18:27:46
【问题描述】:
当您抛出并未处理std::runtime_error 时,终端会自动打印what() 的结果,从而使调试更加容易。示例:
#include <iostream>
int main()
{
throw std::runtime_error("This is an error message.\n");
}
控制台输出:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is an error message.
由此类派生的自定义异常类显示相同的行为,从头开始创建的异常类默认情况下不会这样做。
但是我想创建的异常类不能从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派生。" - 为什么不呢?
-
在 main 中捕获你的异常,然后用它们做你想做的事。我不会依赖运行时为您执行此操作。
-
@NeilButterworth 它迫使我使用某些数据类型或每次都转换它们,它阻止我创建一个我想用于我自己的项目的通用异常类,我想知道如何出于好奇添加此功能。我只是不喜欢那样。否则我可以只使用 std::runtime_error 本身...但是我想要自定义异常类,因为它可以执行某些 std::runtime_error 不能做的事情。
-
@Thynome “但是我想要自定义异常类,因为它可以完成某些 std::runtime_error 不能做的事情。” 请您详细说明一下吗?
-
我不推荐通用异常类。
标签: c++ debugging exception custom-exceptions