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?
It's not possible to throw nothing. You need to throw something. While you may have seen people use the throw
keyword without anything, this just means they are re-throwing the currently handled exception.
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