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?
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++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With