Explain why when you enter 0 and throw a Base exception, it is not caught by the Derived1 block?

 int main() { int number = 0; for (;;) { try { cin >> number; cout << number << " "; switch (number) { case 0: throw Base(); case 1: throw Derived1(); case 2: throw Derived2(); } } catch (Derived1 /*exception*/) { cout << "Exception of derived class" << endl; } catch (Base /*exception*/) { cout << "Exception of Base class" << endl; } } return 0; } 
  • Because Base is not a Derived instance. On the contrary, Derived is an instance of Base. - VladD
  • The question sounds like "why 2 + 2 is not equal to 5". That you first explain where this question came from. Why would it suddenly catch (Derived1) catch Base type exceptions? - AnT
  • @AnT: Connect telepathy :) Obviously, the TS has confused the direction of the is-a relationship. - VladD
  • well edited: guess what inherits from whom only by class names ((( - Alexander

1 answer 1

Because Base not Derived , but Derived is Base .

Now, if you wrote (by the way, intercept exceptions by reference, otherwise you will encounter a truncation )

  catch (Base& /*exception*/) { cout << "Exception of Base class" << endl; } catch (Derived1& /*exception*/) { cout << "Exception of derived class" << endl; } 

then Base and Derived would be caught in the first block, Base .