【发布时间】:2014-02-28 02:14:46
【问题描述】:
如果文件无法打开,我在 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();
}
}
【问题讨论】:
-
我会说这是非常糟糕的做法。我建议返回一个值来指示成功或失败。 如果那不可能抛出异常。
-
另外,如果确实因为无法打开文件而必须退出,退出码应该大于零。
-
非常糟糕的做法,但您至少应该使用非零退出代码来表示失败。
-
这里如何抛出异常?
-
@CaptainObvlious:我建议抛出异常。返回值可以忽略。