C++ exception handling in class hierarchies

前端 未结 3 1556
有刺的猬
有刺的猬 2020-12-11 19:24

In a hierarchy of exception classes, What is the correct ordering of catch statements so as to allow exceptions of more than one class from the hierarchy of exception classe

3条回答
  •  醉话见心
    2020-12-11 19:51

    The correct ordering should be the most derived first. The handlers must be in the order from most derived to the Base class.
    Here's an code example:

    #include 
    
    using namespace std;
    
    class MyException
    {
        public: 
        MyException(int value):mValue(value)
        {
        }
        int mValue;
    };
    
    class MyDerivedException: public MyException
    {
        public: 
        MyDerivedException(int value, int anotherValue):MyException(value),mAnotherValue(anotherValue)
        {
        }
        int mValue;
        int mAnotherValue;
    };
    
    void doSomething()
    {
    
        //Lot of Interesting stuff
    
        //Exception condition
        throw MyDerivedException(10,20);
    }
    
    int main()
    {
        try
        {
            doSomething();
        }
        catch(MyDerivedException &exception)
        {
            cout<<"\nCaught Derived Class Exception\n";
        }
        catch(MyException &exception)
        {
            cout<<"\nCaught Base Class Exception\n";
        }
        return 0;
    }
    

    In the above example the handlers are ordered as Derived class(MyDerivedException) and then the Base class(MyException). If the order of these handlers is reversed then the Base class handler will catch all the exceptions thrown(even if they are of the Derived class). This is because one can always assign a Derived class object/pointer to object/pointer of a Base class without any typecasting or explicit handling.
    Hth.

提交回复
热议问题