Calihog
Calihog

Reputation: 135

Throw exception if the file does not exist in constructor and try/catch it when creating an object in main(), if good - start using the object

I want to open a file in my constructor and read data from it. The check if the file can be opened should be in the constructor (from my point of view) and if there is an exception - throw it and try/catch it in the main, when I try to initialize a new object. But if an exception appears I want to continue asking the user for another try to enter the filename. I've came up with something like this:

fstream fp;

class myClass {
    myClass(const string& n) {
        //try to open a file and read data from it to write it in a list
        fp.open (n, ios::in);
        if (!fp) {
            throw std::runtime_error("Could not open file");
        }
        //use fp to read data and put the data in a list
    }
};

void main () {
    cout << "Please enter input file name: \n";
    string iname = "";
    cin >> iname;
    ifstream ist{iname};
    try {
        myClass obj(iname);
    } catch (std::exception &ex) {
        std::cout << "Ouch! That hurts, because: "
            << ex.what() << "!\n";
    }
    /* if the file is not found or can't be opened for some reason, get back to the 'cin >> iname;' part
       else - just start using obj to do something with it */
}

At the moment the code I've came up with only throws an exception if the entered file name can't be opened and the program ends.

I want the user to be able to enter file name and try create an object with the specified file name. If the file cannot be opened - exception should be thrown in the constructor of the object and he should then be able to enter a new file name. Is it possible to throw an exception in the constructor of the object and catch it in main with a try/catch block only on the object initialization? If no exceptions are thrown, the code after the try/catch block should continue and you could start using the successfully created object?

Upvotes: 1

Views: 10459

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171383

Just use a loop!

  int main () {
    bool done = false;
    cout << "Please enter input file name: \n";
    string iname;
    while (!done && cin >> iname) {
      try {
        myClass obj(iname);
        // use obj ...

        done = true;  // exit the loop
      } catch (std::exception &ex) {
        std::cout << "Ouch! That hurts, because: "
            << ex.what() << "!\n";
      }
    }
  }

Upvotes: 1

Related Questions