Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does throw "nothing" causes program termination?

Tags:

People also ask

Does throw terminate the program?

Simply throwing an exception will not terminate the program, as such. It is what happens after it was thrown that determines what will occur. Show activity on this post. Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not.

Does throw terminate program C++?

In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program. If no user-provided exception handler is present, the compiler provides a default mechanism to terminate the program.

Does program terminate after exception?

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. There are two types of exceptions in Java.

How do you prevent the termination of a program due to an exception?

The uncaught_exception() function is most useful for preventing program termination due to a function that exits with an uncaught exception while another exception is still active. This situation most commonly occurs when a destructor called during stack unwinding throws an exception.


const int MIN_NUMBER = 4;
class Temp
{
public:

    Temp(int x) : X(x)
    {
    }

    bool getX() const
    {
        try
        {
            if( X < MIN_NUMBER)
            {
                //By mistake throwing any specific exception was missed out
                //Program terminated here
                throw ;
            }
        }
        catch (bool bTemp)
        {
            cout<<"catch(bool) exception";

        }
        catch(...)
        {
            cout<<"catch... exception";
        }
        return X;
    }

private:
    int X;
};



int main(int argc, char* argv[])
{
    Temp *pTemp = NULL;
    try
    {
        pTemp = new Temp(3);
        int nX = pTemp->getX();
        delete pTemp;
    }
    catch(...)
    {
        cout<<"cought exception";
    }

    cout<<"success";
    return 0;
}

In above code, throw false was intended in getX() method but due to a human error(!) false was missed out. The innocent looking code crashed the application.

My question is why does program gets terminated when we throw "nothing”?

I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?