c++ - 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 open file in constructor , read data it. check if file can opened should in constructor (from point of view) , if there exception - throw , try/catch in main, when try initialize new object. if exception appears want continue asking user try enter filename. i've came this:

fstream fp;  class myclass {     myclass(const string& n) {         //try open file , read data write in list         fp.open (n, ios::in);         if (!fp) {             throw std::runtime_error("could not open file");         }         //use fp read data , put data in 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! hurts, because: "             << ex.what() << "!\n";     }     /* if file not found or can't opened reason, 'cin >> iname;' part        else - start using obj */ } 

at moment code i've came throws exception if entered file name can't opened , program ends.

i want user able enter file name , try create object specified file name. if file cannot opened - exception should thrown in constructor of object , should able enter new file name. possible throw exception in constructor of object , catch in main try/catch block on object initialization? if no exceptions thrown, code after try/catch block should continue , start using created object?

just use 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 loop       } catch (std::exception &ex) {         std::cout << "ouch! hurts, because: "             << ex.what() << "!\n";       }     }   } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -