在void函数中使用exit进行错误处理是一种好习惯吗? [英] Is it good practice to use exit in void function for error?

查看:54
本文介绍了在void函数中使用exit进行错误处理是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件无法打开,我正在C ++ void函数中使用exit.这样做是一种好习惯吗?

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

推荐答案

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

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.

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

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.

这篇关于在void函数中使用exit进行错误处理是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆