且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在c ++中正确使用exit()?

更新时间:2023-02-17 20:08:29

从函数调用 exit 但是,如果你正在编写一个函数,它可能最终会在一个库中找到一个函数,实例,调用 exit 从一般有坏做法:它是更好的信号错误的调用代码(通过一个特定的返回值或异常为例),让let调用代码决定做什么。 (有些情况下它是完全有效的,例如,如果你正在写一个函数 quit_if_file_not_found ,好,你的用户期待终止。)



在你的case,你的解析函数可能不应该调用 exit :你可能想,例如,在未来的某个时候,你的主要代码要求用户一个不同的文件名,如果解析第一个失败。如果你的解析例程终止了程序,你必须修改你的主要代码和那个函数。如果它发出错误信号,您只需要修改 main 中的逻辑。



不要只是退出,而不打印错误消息或记录像你在上面做的那样,这将使那些不知道如何解决任何问题的沮丧的用户是遇到的代码。)


I have written a simple application that reads a data file, parses the text and then does some processing on that data. The data file is opened in my main() function. Is it good programming practice to use the exit() function if it is determined that the file was not opened properly? eg:

if (!file.is_open() ){
     exit(1);
}

Furthermore, my program has a separate function to parse the data in the file. This function is called by main(). If the function finds an error in the data, I want the program to stop, after printing an error message. In such a situation, is it acceptable to use the exit() function within my parsing function? I am asking this question because, to me, it doesn't seem to be very tidy to allow a function to exit a program on it's own without returning control to the main() function. (I apologize if this question seems pretty obvious.. I'm new to C++ and programming in general).

Calling exit from a function isn't "bad" in the sense that it has well-defined behavior - there's nothing fundamentally wrong in doing so.

But, if you're writing a function that could end up in a library for instance, calling exit from there is bad practice in general: it is much better to signal an error to the calling code (via a specific return value or exception for instance) and let the calling code decide what to do. (There are cases when it's perfectly valid though. e.g. if you're writing a function called quit_if_file_not_found, well, your users are expecting a termination.)

In your case, your parsing function probably shouldn't call exit: you might want, for example, at some point in the future, your main code to ask the user for a different file name if parsing the first one failed. If your parsing routine terminates the program, you have to modify both your main code and that function. If it had signaled an error condition, you'd only have to modify the logic in main.

(And don't just exit without printing an error message or logging something like you're doing above, that will make for frustrated users who can't know how to fix whatever issue it is the code encountered.)