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?
This is expected behaviour. From the C++ standard:
As to why the compiler can’t diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that could in theory be caught by the compiler but in practice are not.