Why doesn't my catch work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <exception>
using namespace std;

class X { virtual void whatever(){}};
class Y : public X {public: int a;};

int main() {
    try{
      X* x = new X;
      X* y = new Y;
      Y* yy;
      yy = dynamic_cast<Y*>(x);
      cout << yy->a;
    } catch(exception& e) {cout << e.what() << endl;}
}


Why doesn't my catch eat the error?
See http://en.wikipedia.org/wiki/Dynamic_cast. An exception is only thrown if converting to a reference type, not a pointer type. A pointer type cast just returns NULL. See http://ideone.com/BdHLl for a working example based on yours.
Topic archived. No new replies allowed.