如果无法打开文件,我在C++ void函数中使用exit.这样做是好的做法吗?
void ReadData()
{
ofstream myfile ("example.txt");
if (! myfile.is_open())
{
cout << "Unable to open file";
exit(0);
}
else {
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
}
Run Code Online (Sandbox Code Playgroud)
这将结束程序,如果调用者可能能够处理错误并继续,则会有点苛刻.退出零(表示成功)是一个非常糟糕的主意.
在C++中报告错误的常用方法是抛出异常.然后调用者可以选择是否处理它,或者是否忽略它并可能终止程序.
| 归档时间: |
|
| 查看次数: |
823 次 |
| 最近记录: |