thrower.cpp

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

using namespace std;

class TellerT {
   public:
      TellerT (string newWhere){ where = newWhere;};
      ~TellerT () {cout << "destructor in " << where << " called" << endl;}
   private:
      string where;
};

void Thrower(int i);
void Middle();
void Last();

int main() {
    for(int i = 0; i < 3; ++i) {

        try {
           Thrower(i);
        } catch (const exception & e) {
           cout << "Caught an " << e.what() << endl;
        } catch (int e) {
           cout << "Caught an int " << e << endl;
        }
        catch (const string & s) {
           cout << "Caught the string " << s << endl;
        }
  
        cout << endl;
    }

    cout << endl << endl;

    try {
       TellerT a{"main try block"};
       Middle();
       cout << "Exiting the try block" << endl;
    } catch (...) {
       cout << "In the exception handler in main" << endl;
    }

    return 0;
}

void Middle() {
   TellerT b{"Middle()"};
   cout << "In middle" << endl;
   Last();
   cout << "Exiting middle" << endl;
}

void Last() {
   TellerT c{"Last()"};
   cout << "Before the throw in last" << endl;
   throw exception {};
   cout << "After the throw in last" << endl;
}

void Thrower(int i) {
   switch (i) {
      case 0: throw 5 ;
      case 1: throw string{"Hello World"} ;
      case 2: throw  logic_error {"An exception was thrown"} ;
   }
   return;
}