考虑以下 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++ 也是否定的。是的,我可以运行一个测试程序,但我想知道在我的编译器有错误的远程情况下行为的语言定义。
不会。只有关联块中抛出的异常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 块中处理
您可以通过对调用方法的异常委托来实现所需的行为