Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use std::cerr and exit() instead of throwing an exception?

Tags:

c++

exception

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?

like image 396
TurboLuke Avatar asked Aug 31 '25 17:08

TurboLuke


1 Answers

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++?

like image 122
CoralK Avatar answered Sep 02 '25 05:09

CoralK