C++ 例如,嵌套try catch中的()更改

C++ 例如,嵌套try catch中的()更改,c++,exception-handling,try-catch,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() { t

我有一个嵌套的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();
   }
}
如您所见,
ex.what()
在函数A中工作正常,并告诉我正确的描述,但在B
ex.what()
中只告诉我
std::exception
。为什么会发生这种情况


我是否在函数A的catch子句中抛出了不同的或错误的内容?如何抛出嵌套异常,以便在B中获得准确的异常描述?

Replace
throw-ex带有
抛出

执行后一种操作将通过引用重新抛出异常
ex
,因此避免了尝试进行值复制时的危险:请参阅


(请注意,即使您编写了
抛出
,也可以修改
ex

您在
a
中抛出异常
ex
的副本。这会导致对象切片,将具体异常转换为
std::exception

要重新显示多态捕获的实际异常,请使用
抛出语句

斯科特·迈尔斯在书中说的话值得记住。您按值抛出,并应按引用捕获。

您是原始异常对象,请尝试

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
  ^^^^^^
}
试试看{
抛出std::runtime_错误(“helloworld”);
}
捕获(标准::异常和例外)
{

关于@StoryTeller answer,我接受你的回答,因为有额外的链接和你最后的观点。吹毛求疵,但我认为你的意思是
throw;
,因为(AFAIK)
throw本身是无效的。请参阅:,
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
  ^^^^^^
}