如果我只是简单地使用throw some_string;
,那么我得到terminate called after throwing an instance of 'std::string'
。我怎样才能得到一些打印输出的字符串值实际显示,例如,terminate called after throwing 'This is wrong'
,或类似的东西?如何用C++打印输出
谢谢。
如果我只是简单地使用throw some_string;
,那么我得到terminate called after throwing an instance of 'std::string'
。我怎样才能得到一些打印输出的字符串值实际显示,例如,terminate called after throwing 'This is wrong'
,或类似的东西?如何用C++打印输出
谢谢。
通常,您应该抛出std::exception.
的子类如果未捕获到异常,大多数C++实现自动打印出调用exception::what()
的结果。
#include <stdexcept>
int main()
{
throw std::runtime_error("This is wrong");
}
随着GCC,此输出:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is wrong
Aborted
你必须从某个地方添加代码来处理抛出的对象。如果你什么都不做,那么程序在调用中止时结束,结果是实现定义的。您的解决方案是在代码中的某处添加一个catch块,例如在主函数中。原因如下
你必须捕获异常
#include <iostream>
#include <string>
int main(int argc, char *argv[]) try
{
throw std::string("This is a test");
return 0;
}
catch(const std::string &s)
{
std::cout << s << std::endl;
}
有趣的函数try-catch块的使用,我忘记了这一点,注意这会导致main的隐式返回值,这意味着main将返回0,这可能不是你想要的,如果你报告错误条件当退出时 – karunski 2012-02-24 03:42:22
其实我试图使用晦涩的形式 - 但我只是把它扔在我的主要func的标准模板 - 我没有考虑返回值,我会假设值是未定义的,因为'返回0 ;'不应该被执行 - 对吧? – 2012-02-24 04:00:16
@AdrianCornish:0的返回值不是来自'return 0;',这是由于在不返回'return'语句的情况下离开main相当于返回0。 – Mankarse 2012-02-24 04:48:55
但Windows。 :( – Arafangion 2012-02-24 02:41:37