Friday, November 19, 2010

Exceptions in Constructors

Given the following program:

  #include <iostream>
  using namespace std;
  struct MyStruct {~MyStruct() {throw 1;}};
  int main() {
    try {
      MyStruct myObject;
      throw 2;
    } catch (int& e) {
      cout << "Caught exception: " << e << endl;
      cout << "About to return" << endl;
      return 0;
Will not print "About to return".

The program will abort after the MyStruct Destructor throws the second exception during the processing of the first. If you comment out the 'throw 1;', you will see the '2' exception being caught and printed out; And then the "About to return" will be printed out.

No comments:

Post a Comment