error2.cpp

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

using namespace std;

void MiddleMan(string phrase, bool doError);
void ErrorRoutine(string phrase, bool doError);

int main() {
   string phrase{"Hello World!"};
   bool boolFlag{true};
  
   do {
      boolFlag = !boolFlag;

      cout << "Top of loop, boolFlag = " << boolalpha << boolFlag << endl;

      try {
         cout << "in the main try block" << endl;
         MiddleMan(phrase, boolFlag);
         cout << "Done in the main try block " << endl;

      } catch (...) {
         cout << endl;
         cout << "In the exception handler for the main" << endl;
      }

      cout << endl << endl;

   } while (!boolFlag);


   return 0;
}

void MiddleMan(string phrase, bool doError) {
 
    cout << "\tIn MiddleMan" << endl;
    try {
        ErrorRoutine(phrase, doError);
    } catch (int x) {
        cout << "\tCaught an exception that produced " << x << endl;
    }
    cout << "\tDone with MiddleMan" << endl;
}


void ErrorRoutine(string phrase, bool doError){
    cout << "\t\tIn the ErrorRoutine" << endl;
    if (doError) {
       cout << phrase.at(phrase.size() + 2) << endl;
    }
    cout << "\t\tDone in the ErrorRoutine" << endl;
}