Chapter Twenty: Object Destruction and Error Handling
Before you run the code in C++, try to predict the output of the following code:
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructing an object of Test " << endl; }
~Test() { cout << "Destructing an object of Test "  << endl; }
};
int main() {
try {
Test t1;
throw 10;
} catch(int i) {
cout << "Caught " << i << endl;
}
}
The output of this code is:
Constructing an object of Test
Destructing an object of Test
Caught 10
When the compiler throws an exception, the code's destructor functions will be called to remove the objects whose scope ends with the entire block. This destructor is called before the compiler executes the exception handler code. For this reason, the code above gives you the output “Caught 10” after “Destructing an object of Test.” How do you think the compiler will act when it identifies an exception in the constructor? Consider the following example:
#include <iostream>
using namespace std;
class Test1 {
public:
Test1() { cout << "Constructing an Object of Test1" << endl; }
~Test1() { cout << "Destructing an Object of Test1" << endl; }
};
class Test2 {
public:
// Following constructor throws an integer exception
Test2() { cout << "Constructing an Object of Test2" << endl; 
throw 20; }
~Test2() { cout << "Destructing an Object of Test2" << endl; }
};
int main() {
try {
Test1 t1;  // Constructed and destructed
Test2 t2;  // Partially constructed
Test1 t3;  // t3 is not constructed as this statement never gets executed
} catch(int i) {
cout << "Caught " << i << endl ;
}
}
The output of the above program is:
Constructing an Object of Test1
Constructing an Object of Test2
Destructing an Object of Test1
Caught 20
The compiler calls the destructor only when it uses completely constructed objects. If the constructor of the object leaves an exception, the compiler does not call for the destructor. Before you execute the following program, try to predict its outcome.
#include <iostream>
using namespace std;
class Test {
static int count;
int id;
public:
Test() {
count++;
id = count;
cout << "Constructing object number " << id << endl;
if(id == 4)
throw 4;
}
~Test() { cout << "Destructing object number " << id << endl; }
};
int Test::count = 0;
int main() {
try {
Test array[5];
} catch(int i) {
cout << "Caught " << i << endl;
}
}