Click to See Complete Forum and Search --> : C++ Exception Handling: The wrong catch statement catches an exception! Why?


KevinHall
February 18th, 2003, 11:52 AM
Q: The wrong catch statement catches an exception in the following code! Why?


#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;
}


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!

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:


#include &lt;iostream&gt;

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;
}

<br><br>