classThrow.cpp

URL: http://147.64.242.52/~bennett/class/cmsc2040/fall2026/notes/except/code/classThrow.cpp
 
#include <iostream>
#include <exception>

using namespace std;

class ThrowInConstructor {
    public:
        ThrowInConstructor() {
           cout << "In the constructor for ThrowInConstructor" << endl;
           data = new int[10];

           // this is silly, but needed so that the compiler will not 
           // optomize the code away
           for(int i = 0; i < 10; ++i) {
               data[i] = i;
           }

           if (data[2] == data[3]) {
              data[2] = 4;   
           }

           throw runtime_error{"Throw in constructor"};
        }

        ~ThrowInConstructor() {
           delete [] data;
        }
    private: 
        int * data;
};

class ThrowInDestructor {
   public:
       ~ThrowInDestructor() {
          throw runtime_error{"Throw in Destructor"};
       }
};

int main() {

    cout << "Creating a class that will throw in the constructor" << endl;
    try {
        ThrowInConstructor a;
    } catch (...){
        cout << "Caught an int" << endl;
    }

    try {
       ThrowInDestructor a;
    } catch (...) {
       cout << "In the catch block" << endl;
    }

    return 0;
}