我想在我的构造函数中打开一个文件并从中读取数据。检查文件是否可以打开应该在构造函数中(从我的角度来看),如果有异常 - 当我尝试初始化一个新对象时,抛出它并在 main 中尝试/捕获它。但如果出现异常,我想继续要求用户再次尝试输入文件名。我想出了这样的事情:
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 block 在 main 中捕获它?如果没有抛出异常,try/catch block 之后的代码应该继续,您可以开始使用成功创建的对象吗?
最佳答案
只需使用一个循环!
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";
}
}
}
关于c++ - 如果文件在构造函数中不存在则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果正确 - 开始使用该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057028/