Mock Mock - 4 years ago 113
C++ Question

Classes and Exception Handling In C++

I've run across a coding problem that I'm having trouble understanding (note the line tagged with //-):

#include <iostream>

using namespace std;

class X { };

class X0 { };
class X1: public X0 { };
class X2: public X1 { };

void f(int i) {
if (i == 0) {
throw X0();
} else if (i == 1) {
throw X1();
} else if (i == 2) {
throw X2();
} else {
throw X();

int main(int argc, char* argv[]) {
try {
f(0); //-
} catch (X1) {
cout << "A" << endl;
} catch (X2) {
cout << "B" << endl;
} catch (X0) {
cout << "C" << endl;
} catch (...) {
cout << "D" << endl;

The output of this code is C, as expected. If I change the tagged line to "f(1);" the output is A, also as expected.

However, if I change the tagged line to "f(2);" the answer is also A, and I'm not understanding why. I feel like it may have something to do with the scope of the destructors, but my attempts to find information on it haven't been successful because I'm not entirely sure what to study. Would anyone be able to explain what is happening here, or just the name of concept this problem is illustrating so I can research it? Any help is appreciated.

Answer Source

An X2 inherits from X1 and so "is" an X1, and the catch block for X1 is first so triggers before we reach the X2 one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download