error4.cpp

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

using namespace std;

int main() {
   string phrase{"Hello World!"};


   for(size_t i = 0; i <= phrase.size(); ++i) {
      try {

         cout << i << " '"  << phrase.at(i) << "'" << endl;

         // cause an exception with stoi
         if (i == 4) {
             string badInt{"xxx"};
             int j = stoi(badInt);
             cout << " j = " << j << endl;
         } else if (i == 5) {
             ifstream foo;
             foo.exceptions(ifstream::failbit);
             foo.open("hello");
         }

      } catch (const out_of_range & e) {
          cout << "Caught an  out of range exception" << endl;
          cout << "It is " << e.what() << endl;
          cout << endl << endl;
      } catch (const runtime_error & e) {
          cout << "Caught a runtime_error" << endl;
          cout << "It is " << e.what() << endl;
          cout << endl << endl;
      /*} catch (const ios_base::failure & e) {
          cout << "Caught an ios_base::failure" << endl;
          cout << "It is " << e.what() << endl;
          cout << endl << endl;
      */
      } catch (...) {
          cout << "Caught a generic exception " << endl;
          cout << endl << endl;
      }
   }

   cout << "This line will always print out" << endl;

   return 0;
}