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