C ++ exception handling in class hierarchies

In the hierarchy of exception classes: What is the correct order of catch statements so that you can catch exceptions from more than one class from the hierarchy of exception classes?

Is it most important for the base or base for most derivatives?

+5
source share
3 answers

Most of the first. Handlers are mapped in the order in which they are displayed, so first you need the most specific ones.

+4
source

My answer matches the linux compiler and hopefully it should be true for everyone. The catch order depends on two factors:

(1) First choose the first option ; If the base class appears before the derivative, it will be given a choice. Some compilers warn about this, some do not;

(2) Type of inheritance ; Either public or non-public (private / secure)

struct B {}; struct D : B {}; struct DD : D {}; int main() { for(int i = 0; i < 3; i++) { try { switch(i) { case 0: throw new B; case 1: throw new D; case 2: throw new DD; } } catch(B *o) { cout<<"B* caught\n"; } catch(D *o) { cout<<"D* caught\n"; } catch(DD *o) { cout<<"DD* caught\n"; } } } 

(1) In the above code, it always catches B., if you change the order with the trap DD, D, B, then it will meet your expectations when preference will be given to Derived classes.

(2) Now replace 'struct' with 'class' or change the inheritance to private / protected; In the above code, regardless of order, catches will match the type of throw. It will be so strict that even if you delete any of the catch of the Derived class, it will not be caught by the base class.

+1
source

Proper ordering should be the most derivative first. Handlers should be in order from most received to the base class.
Here is a sample code:

 #include <iostream> 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 the Derived class (MyDerivedException), and then the base class (MyException). If the order of these handlers is canceled, then the Base class handler will catch all exceptions (even if they belong to the Derived class). This is due to the fact that you can always assign an object / pointer of the Derived class to an object / pointer of the base class without any machine or explicit processing. Hth.

0
source

All Articles