在void函数中使用exit是错误的好习惯吗?

Man*_*ish 0 c++ exit

如果无法打开文件,我在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)

Mik*_*our 5

这将结束程序,如果调用者可能能够处理错误并继续,则会有点苛刻.退出零(表示成功)是一个非常糟糕的主意.

在C++中报告错误的常用方法是抛出异常.然后调用者可以选择是否处理它,或者是否忽略它并可能终止程序.