Under exceptional circumstances, I want my program to stop processing, output an error to std::cerr
, clean up, and exit.
However, calling exit()
will not call all the destructors of any objects that have been constructed. I would like to have the destructors called nicely, so I wrapped all the code in a try-catch
block, something like this:
int main(int argc, char** argv){
try {
bool something_is_not_right = false;
/* lots of variables declared here */
/* some code that might set something_is_not_right to true goes here */
if(something_is_not_right){
std::cerr << "something is not right!!!" << std::endl;
throw '\0'; // dummy unused variable for throwing.
}
}
catch (...) {}
return 0;
}
In this way, I get guaranteed destruction of all my variables. But I can't seem to find a way to get C++ to throw
nothing. throw;
has a special meaning in C++; it isn't throwing nothing.
Is there a way to throw
nothing?
abnormal_program_termination
? – Trainexit()
might not be the right thing to do in the first place. – Francothrow;
without anything if you handled an exception in acatch
block and want to rethrow to the caller. – Mobergstd::terminate
is called. – Syndicreturn 0
will also call all destructors. If you want the other, just create your own exception class to be handled as termination by abnormal condition. – Mikvahsomething_is_not_right = true
, why notthrow something_is_not_right
? – Francosomething_is_not_right
is always false when thrown. – Selinskisomething_is_not_right
can instead be astruct something_is_not_right : public std::runtime_error { using std::runtime_error::runtime_error; }
. The point is that you already have some logic that handles an error using a boolean variable. Why not replace setting abool
totrue
with throwing an exception? You've already succumbed to using exceptions anyway. – Francobool
was just a simple way to illustrate my predicament. – Selinski