25

考虑以下 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++ 也是否定的。是的,我可以运行一个测试程序,但我想知道在我的编译器有错误的远程情况下行为的语言定义。

4

3 回答 3

27

不会。只有关联块中抛出的异常try才会被catch块捕获。

于 2011-08-06T14:19:16.170 回答
9

不,它不会,层次结构向上的封闭 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;
}
于 2011-08-06T14:24:20.277 回答
2

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

您可以通过对调用方法的异常委托来实现所需的行为

于 2011-08-06T14:25:48.790 回答