在catch块中抛出的异常会被后面的catch块捕获吗?

Will exception thrown in catch block be caught by later catch blocks?

本文关键字:catch 异常      更新时间:2023-10-16

考虑以下c++代码:

try {
  throw foo(1);
} catch (foo &err) {
  throw bar(2);
} catch (bar &err) {
  // Will throw of bar(2) be caught here?
}

我希望答案是否定的,因为它不在try块内,我在另一个问题中看到Java的答案是否定的,但我想确认c++也是否定的。是的,我可以运行一个测试程序,但我想知道在远程情况下,我的编译器有一个错误的行为的语言定义。

No。只有在相关的try块中抛出的异常才能被catch块捕获。

不,它不会,在层次结构之上的封闭catch块将能够捕获它。

样本的例子:

void doSomething()
{
    try 
    {
       throw foo(1);
    } 
    catch (foo &err) 
    {
       throw bar(2);
    } 
    catch (bar &err) 
    {
       // Will throw of bar(2) be caught here?
       // NO It cannot & wont 
    }
}
int main()
{
    try
    {
        doSomething();
    }
    catch(...)   
    {
         //Catches the throw from catch handler in doSomething()
    }
    return 0;
}

不,catch块处理最近的异常,所以如果你尝试…catch (Exception &exc)…catch (SomethingDerived &derivedExc)异常将在&exc块中处理

您可以通过将异常委托给调用方法

来实现所需的行为