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

Wil*_*mKF 23 c++ exception try-catch rethrow

考虑以下C++代码:

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

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

Pup*_*ppy 24

不可以.try块中只能捕获相关块中抛出的异常catch.


Alo*_*ave 9

不,它不会,一个封闭的捕获块向上层次结构将能够捕获它.

示例示例:

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;
}
Run Code Online (Sandbox Code Playgroud)