为什么以下不能处理被重新抛出的异常?我尝试了所有的组合,但没有一个会在最后一次捕获中显示输出,所以我很困惑!
Derived D;
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
Derived D;
try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
Derived D;
try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
Derived D;
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}
Run Code Online (Sandbox Code Playgroud)
Lig*_*ica 17
重新抛出不是由同一个try-catch
块处理的.它被抛到调用范围.
在[except.throw]
(2003年的措辞):
没有操作数的throw-expression重新抛出正在处理的异常.
和:
抛出异常时,控制转移到具有匹配类型的最近的处理程序(15.3); "nearest"表示最后由控制线程输入复合语句,ctor-initializer或函数体后面的处理程序,但尚未退出.
您的try
块已退出,因此其处理程序不是候选者.因此,catch
代码中的所有块都不能处理重新抛出.
不可否认,这是相当混乱的措辞.
Rethrown异常应该被其他一些try..catch
块捕获,而不是同try
一块的catch处理程序.看这个例子:
using namespace std;
class Base
{
public:
virtual ~Base(){}
};
class Derived : public Base
{
};
void f()
{
try
{
throw Derived();
}
catch(Derived& ex)
{
cout<<"Caught in f\n";
throw;
}
}
int main()
{
try
{
f();
}
catch(Base& b)
{
cout<<"Caught in main\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
陷入f
主要抓到了