Rethrowing exceptions

前端 未结 3 1005
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 11:17

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!

相关标签:
3条回答
  • 2021-02-13 11:51

    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

    0 讨论(0)
  • 2021-02-13 11:52

    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.

    0 讨论(0)
  • 2021-02-13 11:53

    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.

    0 讨论(0)
提交回复
热议问题