为什么重新抛出异常会丢弃' what()'?

时间:2017-06-18 09:00:24

标签: c++ exception g++

我在Windows 10上使用MinGW gcc(或g ++)7.1.0。

通常,抛出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 个答案:

答案 0 :(得分:1)

是什么让你认为重新抛出异常会丢弃&#39; what()&#39;?你永远不会检查重新抛出后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;
    }
}