Is it good practice to use exit in void function for error?

我只是一个虾纸丫 提交于 2021-02-11 15:49:56

问题


I am using exit in C++ void function if file cannot be opened. Is it good practice to do so?

 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();
      }
 }

回答1:


That will end the program, which is a bit harsh if the caller might be able to handle the error and continue. Exiting with zero (indicating success) is a very bad idea.

The usual way to report an error in C++ is to throw an exception. Then the caller can choose whether to handle it, or whether to ignore it and perhaps terminate the program.




回答2:


Generally, a reusable function should not abort or exit the program unless you know the caller will be unable to handle the failure in any reasonable way. Otherwise, it is "rude" to your caller to exit because of a failure that the caller could handle.

For example, a function that looks for a given file may fail because the file doesn't exist, but maybe the file is optional (a cache file, for example), in which case the failure is harmless to the caller.

Instead of exiting, consider returning an error code or throwing an exception instead.




回答3:


If you choose to use exit, you will want to use something other than 0, such as

exit(1);

The good thing about this is that a script calling your program can detect an error easily with the return code.




回答4:


If you plan to write code that others will use, it isn't a good practice to use exit(). At worse, it can get you in a lot of trouble with your customer or user base.

Case in point: There was a commercial database library some time ago that took this approach of exiting the application if something went wrong. Needless to say, there were a lot of complaints by the users of the library, and the arrogance that the authors showed concerning this basically put them on the outs with their users.

Bottom line is that it shouldn't be up to you (the library author) to decide to pull the rug out from under a running program just because you feel the error is severe. Instead return an error or throw an exception.



来源:https://stackoverflow.com/questions/22084861/is-it-good-practice-to-use-exit-in-void-function-for-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!