如果文件在构造函数中不存在,则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果好 - 开始使用该对象

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

本文关键字:如果 开始 对象 创建对象 不存在 构造函数 文件 抛出异常 并在 main      更新时间:2023-10-16

我想在我的构造函数中打开一个文件并从中读取数据。检查文件是否可以打开应该在构造函数中(从我的角度来看),如果有异常 - 当我尝试初始化一个新对象时,主要抛出它并尝试/捕获它。但是,如果出现异常,我想继续要求用户再次尝试输入文件名。我想出了这样的东西:

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 */
}

目前,我想出的代码仅在无法打开输入的文件名并且程序结束时才会引发异常。

我希望用户能够输入文件名并尝试使用指定的文件名创建对象。如果无法打开文件 - 应在对象的构造函数中引发异常,然后他应该能够输入新的文件名。是否可以在对象的构造函数中抛出异常,并在对象初始化时使用 try/catch 块在 main 中捕获它?如果没有引发异常,try/catch 块后面的代码应该继续,你可以开始使用成功创建的对象了吗?

只需使用循环!

  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";
      }
    }
  }
相关文章: