Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible in C++ to throw nothing?

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?

like image 502
Bernard Avatar asked Apr 28 '17 08:04

Bernard


1 Answers

No

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.

like image 111
nvoigt Avatar answered Sep 18 '22 17:09

nvoigt