Rethrowing exceptions

谁说我不能喝 提交于 2020-01-01 04:14:43

问题


Why doesn't the following doesn't handle the exception that was rethrown? I tried all the combinations but none of them would show the output in last catch so I'm confused!

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;
}

回答1:


The re-throw is not handled by the same try-catch block. It's thrown up to the calling scope.

In [except.throw] (2003 wording):

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

and:

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.

Your try block has exited, so its handlers are not candidates. Thus, none of the catch blocks in your code may handle the re-throw.

Admittedly this is rather confusing wording.




回答2:


Rethrown exception is supposed to be caught by some other try..catch block, not the catch handler of the same try block. See this example:

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;
}

output is:

Caught in f

Caught in main




回答3:


This should work :

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;
}

As other said, the rethrow will rethrow the same exception out of the catch block.



来源:https://stackoverflow.com/questions/6185957/rethrowing-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!