0

This might be a to general question, however I am trying to learn C++ in the last few days and what I have noticed in a lot of example code, is, if errors are handled, the program is not aborted in that case.

So for example, I just have a wrong command line argument, I have seen code like:

if (argument wrong){
   std::cerr << "Invalid argument\n";
}

But there is no aborting of the program. In my C code I would usually do

exit(EXIT_FAILURE)

So is this wrong to use in C++ or how should I handle these situations?

malajedala
  • 867
  • 2
  • 8
  • 22
  • 1
    That totally depends on the desired behaviour of your application. If you have default values that you can fallback to when an argument is wrong, then, well, you can continue indicating clearly what you are doing to the user. If it doesn't make sense to continue without that argument, then you must abort. – Baris Demiray Oct 09 '18 at 12:42
  • It is up to you what to do, but you are right, it is not very common to terminate program. – Michał Walenciak Oct 09 '18 at 12:43

1 Answers1

3

You can just return from your main() function, and your program will shut down gracefully, and clean up after itself. exit() is actually a fairly abrupt way to terminate. Things won't get cleaned up.

jwismar
  • 12,164
  • 3
  • 32
  • 44
  • The hard part is getting back to `main`. Sometimes you can be pretty far down the call stack. – NathanOliver Oct 09 '18 at 12:44
  • That's true. But I was thinking that if you're validating command line arguments, it seems likely that you're somewhere fairly close to `main()`. – jwismar Oct 09 '18 at 12:45
  • Oh yeah, missed the command line argument part. – NathanOliver Oct 09 '18 at 12:46
  • Ok, thanks, but what do you mean it is hard to get back to main function? – malajedala Oct 09 '18 at 15:32
  • Ok so to clarify, lets say somewhere in my code is an error, I have to return.. and then go all the way back to my main function, and there probably do some checkups if it was returned due to an error? – malajedala Oct 09 '18 at 16:22
  • For a more in-depth discussion, take a look at the linked question above, https://stackoverflow.com/questions/30250934/how-to-end-c-code. It goes through a number of different options that are available. – jwismar Oct 09 '18 at 16:25