重新抛出后,我丢失了异常信息,在上层获得的异常对象就像是全新的。请告知,我如何将信息保留在抛出站点中填充的异常对象中。这是下面的代码
#include <iostream>
#include <stdexcept>
void h()
{
std::cerr<<"h() throwing exception" << std::endl;
throw std::runtime_error ("dummy exception for no reason");
return;
}
void g()
{
try {
h();
}
catch ( const std::exception &ex)
{
std::cerr<<"g() : caught exception : " << ex.what() << std::endl;
throw ex;
}
return;
}
void f()
{
try {
g();
}
catch ( const std::exception &ex)
{
std::cerr<<"f() : caught exception : " << ex.what() << std::endl;
throw ex;
}
return;
}
int main(int ac, char **av)
{
try {
f();
}
catch ( const std::exception &ex)
{
std::cerr<<"main() : caught exception : " << ex.what() << std::endl;
return -1;
}
return 0;
}
输出
h() throwing exception
g() : caught exception : dummy exception for no reason
f() : caught exception : std::exception
main() : caught exception : std::exception