繁体   English   中英

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

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

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

不可以。只有关联的try块中抛出的异常才可能被catchcatch

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

示例示例:

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块中处理

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM