为什么重新抛出异常会丢弃"what()"给出的信息?

Why does rethrowing an exception discards the information given by 'what()'?

本文关键字:信息 what 抛出异常 为什么      更新时间:2023-10-16

我在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()呢?

是什么让你认为重新抛出异常会丢弃"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;
}
}