2017-06-18 77 views
0

我使用MinGW的GCC(或g ++)7.1.0在Windows 10为什么重新抛出异常会丢弃'what()'给出的信息?

通常,抛出std::runtime_error示出了这样的信息:

terminate called after throwing an instance of 'std::runtime_error' 
    what(): MESSAGE 

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 

但下面的代码仅示出了最后两行和what()信息丢失:

#include <stdexcept> 

using namespace std; 

int main() { 
    try { 
     throw runtime_error("MESSAGE"); 
    } catch (...) { 
     throw; 
    } 
} 

所以以上仅输出的代码:

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 

如果我用const exception&,const runtime_error&(或没有const,没有&,或没有这两个)替换...,会发生同样的情况。

据我所知,throw;重新抛出当前捕获的异常。那为什么不显示what()

+1

是什么让你认为重新抛出异常丢弃通过“什么()”中给出的信息?你再也不检查什么()会在重新抛出后返回。显示“此应用程序已请求”消息,因为您未捕获异常导致的程序被终止。 '什么()'不应该被打印。 – VTT

+4

怪Windows。 http://ideone.com/UVRna0 –

+0

@VTT也许这是关于重新说明的东西......我知道异常对象中的信息是IS,并且手动输出信息确实有效,但是如果'what()自动显示像正常? – TRCYX

回答

1

是什么让你认为重新抛出的异常抛弃了'what()'给出的信息?您再也不会检查what()在重新投掷后返回的内容。显示消息This application has requested...是因为未捕获的异常导致程序终止。 what()内容不应该自动打印。

您可以打印what()价值回归没有任何问题:

#include <stdexcept> 
#include <iostream> 

int main() 
{ 
    try 
    { 
     try 
     { 
      throw ::std::runtime_error("MESSAGE"); 
     } 
     catch (...) 
     { 
      throw; 
     } 
    } 
    catch(::std::exception const & exception) 
    { 
     ::std::cout << exception.what() << ::std::endl; 
    } 
} 
+0

如果打算手动打印什么(),我会接受它。好吧,这似乎有点累人。 – TRCYX

+0

@TRCYX注意到,如果没有捕获异常并让程序崩溃导致未捕获的异常,则可能会产生其他麻烦的后果,例如调用析构函数被忽略并且没有进行适当的清理。 – VTT

+0

确实。不应该在真正的节目中这样做,但对这些玩具程序仍然感到有点奇怪。 – TRCYX

相关问题