gpt4 book ai didi

c++ - 重新抛出异常

转载 作者:IT老高 更新时间:2023-10-28 23:11:20 27 4
gpt4 key购买 nike

为什么以下不处理被重新抛出的异常?我尝试了所有组合,但没有一个会显示最后一次捕获的输出,所以我很困惑!

Derived D;

try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}

Derived D;

try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}

Derived D;

try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}

Derived D;

try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}

最佳答案

重新抛出不是由相同的 try-catch block 处理。它被抛出到调用范围。

[except.throw](2003 年措辞)中:

A throw-expression with no operand rethrows the exception being handled.

和:

When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); “nearest” means the handler for which the compound-statement, ctor-initializer, or function-body following the try keyword was most recently entered by the thread of control and not yet exited.

你的 try block 已经退出,所以它的处理程序不是候选的。因此,代码中的任何 catch block 都不能处理重新抛出。

诚然,这是相当令人困惑的措辞。

关于c++ - 重新抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com