Q: The wrong catch statement catches an exception in the following code! Why?
A: No, the code works the way it is supposed to. When a thrown class encounters a parent class in an a catch statement, the class will be recast and copied -- you will not be able to recast a caught pointer back to the original type!Code:#include <iostream> using namespace std; class A { }; class B : public A { }; int main() { B b; try { throw b; } catch (A& ea) { cout << "Caught an instance of A" << endl; } catch (B& eb) { cout << "Caught an instance of B" << endl; } return 0; }
Catching happens on a "first come, first serve" basis. The first catch statement that can match will. In order to get the above code to work as expected, the catch statement for the B class needs to occur before the catch statement for the A class:
Code:#include <iostream> using namespace std; class A { }; class B : public A { }; int main() { B b; try { throw b; } catch (B& eb) { cout << "Caught an instance of B" << endl; } catch (A& ea) { cout << "Caught an instance of A" << endl; } return 0; }




Reply With Quote