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
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.)