dev*_*sih 29 c++ exception-handling try-catch
我有一个嵌套的try-catch代码,如下所示:
void A()
{
try
{
//Code like A = string(NULL) that throws an exception
}
catch(std::exception& ex)
{
cout<<"in A : " << ex.what();
throw ex;
}
}
void B()
{
try
{
A();
}
catch(std::exception& ex)
{
cout<<"in B : " << ex.what();
}
}
Run Code Online (Sandbox Code Playgroud)
运行后我得到了这个结果:
in A: basic_string::_M_construct null not valid
in B: std::exception
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,ex.what()在函数A中正常工作并告诉我正确的描述,但在B中ex.what()告诉我std::exception.为什么会这样?
我在函数A的catch子句中抛出了不同或错误的东西吗?如何抛出嵌套异常以便我可以在B中获得确切的异常描述?
Sto*_*ica 32
你是抛出异常的副本ex在A.这导致对象切片将具体异常转化为std::exception.
要重新抛出您以多态方式捕获的实际异常,请使用该throw;语句.
值得记住Scott Meyers在他的书中所说的内容.你按值抛出,应该通过引用捕获.
你正在切片原始的异常对象,尝试使用
try {
throw std::runtime_error("Hello world");
}
catch (std::exception& ex)
{
cout << "in A : " << ex.what();
throw; // Rethrows the original exception - no copy or slicing
^^^^^^
}
Run Code Online (Sandbox Code Playgroud)