正在重试异常



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

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块处理的。它被抛出到调用范围。

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

没有操作数的抛出表达式会重新引发正在处理的异常。

和:

当抛出异常时,控制权将转移到具有匹配类型的最近处理程序(15.3);"最近的"表示复合语句、ctor初始值设定项或函数体后面的处理程序try关键字最近由控件的线程输入,尚未退出

您的try块已退出,因此其处理程序不是候选程序。因此,代码中的catch块都不能处理重新抛出。

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

Rethrown异常应该由其他try..catch块捕获,而不是由同一try块的捕获处理程序捕获。参见此示例:
using namespace std;
class Base
{
public:
    virtual ~Base(){}
};
class Derived : public Base
{
};
void f()
{
    try
    {
        throw Derived();
    }
    catch(Derived& ex)
    {
        cout<<"Caught in fn";
        throw;
    }
}
int main()
{
    try
    {
        f();
    }
    catch(Base& b)
    {
        cout<<"Caught in mainn";
    }
    return 0;
}

输出为:

在中捕获

在主中捕获

这应该有效:

Derived D;

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

正如其他人所说,rethrow将从catch块中重新抛出相同的异常。

最新更新