4

I'm relatively new to C++ and I am just wondering, what are the main differences between just throwing an exception or writing std::cerr and exit()? I know that if a exception isn't caught the program will exit. Are there any use cases for std::cerr or should I always throw exceptions? Or should I never use std::cerr in general? Are there some best practices for this?

throw std::runtime_error("runtime error msg");

OR

std::cerr << "cerr error msg";
exit(1);                      

Are both versions OK?

TurboLuke
  • 65
  • 3
  • 5
  • 5
    The difference is that an exception can be caught. It does not neccessarily end your program, only if no one catches it. – Nidhoegger Jun 01 '19 at 11:17
  • Depends. If your there is any chance at all that the caller can correct whatever caused the error to occur, then it is probably better to use an exception (which will cause termination if the caller doesn't catch and handle the exception). If there is zero chance that a caller can correct the cause of the error, then exiting is better than throwing an exception. [Note: in multi-threaded programs, `exit()` shouldn't be called]. – Peter Jun 01 '19 at 14:56
  • You have multiple questions here. Please choose either "exceptions vs. exit" or "how/when to use `std::cerr`" for this question, and move the other to a new question. (Since there is an answer already, you should keep the question that matches it.) If you do not see why the questions are independent, consider the code `std::cerr << "cerr error msg"; throw std::runtime_error("runtime error msg");`. – JaMiT Jun 01 '19 at 15:28

1 Answers1

5

The main difference between the two, is that you can catch and handle exception (raise with throw). There are two pros for this action:

A. You can throw an exception and handle it without crashing your program.

B. When handling exception, they will automatically call the destructors of your objects. For example:

try {
    A a;
    throw runtime_error("A"); // Throw exception A
} catch (...) { // Catch exception A & Call a's object destructor.
    throw runtime_error("B"); // Throw exception B and crush (if no one else catch it).
}

You want to use the throw and not the exit(1) option, if you think about future working on this code (or if someone else needs to continue your work on this code).

For more details please see: Are destructors run when calling exit()? & Are destructors called after a throw in C++?

Coral Kashri
  • 3,436
  • 2
  • 10
  • 22