如果文件無法打開,我正在使用C++ void函數中的exit。這是否是一個好習慣?在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();
}
}
我會說這是非常糟糕的做法。我建議返回一個值來表示成功或失敗。 **如果**不可能拋出異常。 –
另外,如果由於無法打開文件而確實必須退出,則退出代碼應該大於零。 – Brian
非常不好的做法,但您至少應該使用非零退出代碼來表示失敗。 – Csq