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;
}
在上述代码中,getX()方法原本意图抛出false
,但由于人为疏忽,漏写了false。这看似无害的代码却让应用程序崩溃。
我的问题是,当我们抛出“什么都没有”的时候,程序为什么会终止?
我有一点理解,throw;
基本上是"重新抛出",必须在异常处理程序(catch)中使用。在任何其他地方使用这个概念将导致程序终止,那么为什么编译器在编译期间不发出警告呢?