Rethrowing exceptions

前端 未结 3 999
伪装坚强ぢ
伪装坚强ぢ 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

提交回复
热议问题