2012-02-24 170 views
2

如果我只是简单地使用throw some_string;,那么我得到terminate called after throwing an instance of 'std::string'。我怎样才能得到一些打印输出的字符串值实际显示,例如,terminate called after throwing 'This is wrong',或类似的东西?如何用C++打印输出

谢谢。

回答

3

通常,您应该抛出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 
+1

但Windows。 :( – Arafangion 2012-02-24 02:41:37

1

你必须从某个地方添加代码来处理抛出的对象。如果你什么都不做,那么程序在调用中止时结束,结果是实现定义的。您的解决方案是在代码中的某处添加一个catch块,例如在主函数中。原因如下

  1. 您可以捕获您投掷的对象并构造一个有意义的错误消息。
  2. 默认行为导致立即终止程序,而无需展开堆栈并清理。抛出的对象必须在主返回之前的某处被捕获以避免这种情况。
0

你必须捕获异常

#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; 
} 
+1

有趣的函数try-catch块的使用,我忘记了这一点,注意这会导致main的隐式返回值,这意味着main将返回0,这可能不是你想要的,如果你报告错误条件当退出时 – karunski 2012-02-24 03:42:22

+0

其实我试图使用晦涩的形式 - 但我只是把它扔在我的主要func的标准模板 - 我没有考虑返回值,我会假设值是未定义的,因为'返回0 ;'不应该被执行 - 对吧? – 2012-02-24 04:00:16

+0

@AdrianCornish:0的返回值不是来自'return 0;',这是由于在不返回'return'语句的情况下离开main相当于返回0。 – Mankarse 2012-02-24 04:48:55