如果文件在构造函数中不存在,则抛出异常,并在 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
我想在我的构造函数中打开一个文件并从中读取数据。检查文件是否可以打开应该在构造函数中(从我的角度来看),如果有异常 - 当我尝试初始化一个新对象时,主要抛出它并尝试/捕获它。但是,如果出现异常,我想继续要求用户再次尝试输入文件名。我想出了这样的东西:
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";
}
}
}
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 如果没有malloc,链表实现将失败
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- C++擦除(如果存在)
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- 如果绝对没有调用成员函数,是否允许使用不完整类型的向量?如果是这样,从什么时候开始
- 如果P从root路径开始,为什么STD :: filesystem :: path :: append替换当前路径
- 如果文件在构造函数中不存在,则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果好 - 开始使用该对象
- 如果旧工作已经完成,如何开始新工作
- 如果所有路径都有相同的长度,如何开始Edmonds-Karp实现
- 如何检查从mx文件,如果Matlab开始与GUI
- OpenGL红皮书-如果枚举默认为整数,从0开始,glBindVertexArray如何绑定到保留值0
- 如果我们从某个地址开始,我们如何确定变量在整个程序中占据的地址