Exception Handling - Example 4 - handling a file open error

// File: eh4.cpp

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
   bool file_ok = false;
   ifstream input_file;
   while (file_ok == false)
   {
      try
      {
         input_file.open("/data/input.fil");
         if (input_file)
         {
            cout << "Ok, I got it\n";
            file_ok = true;
         }
         else throw(string("Can't open input.fil"));
      }
      catch (const string& errmsg)
      {
         cout << errmsg << " Try again?\n";
         char yn;
         cin >> yn;
         if (yn == 'y')
         {
            input_file.clear();
            input_file.open("c:/deanza/data/input.fil");
            if (!input_file)
            {
               cout << "I'm outa here\n";
               break;
            }
            else
            {
               cout << "I got it the second time\n";
               file_ok = true;
            }
         }
         else break;
      }
   }

   cout << "*** End of Program ***\n";
   system("pause");
   return 0;
}


Sample Execution

 ******  Sample Run 1 ******

Ok, I got it
*** End of Program ***


******  Sample Run 2 ******

Can't open input.fil file.  Try again? n
*** End of Program ***


******  Sample Run 3 ******

Can't open input.fil file.  Try again? y
I got it the second time
*** End of Program ***