为什么会抛出“无”导致程序终止? [英] why does throw "nothing" causes program termination?

查看:145
本文介绍了为什么会抛出“无”导致程序终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

在上述代码中, throw false getX()方法,但由于人为错误(!) false 被遗漏。无辜的代码崩溃了应用程序。

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"?

throw; 基本上是rethrow,必须在异常处理程序(catch)中使用这个概念在任何其他地方会导致程序终止,

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?

推荐答案

这是预期的行为从C ++标准:

This is expected behaviour. From the C++ standard:


如果当前没有处理
的异常,则执行throw-expression
,无操作数调用
terminate()(15.5.1)。


If no exception is presently being handled, executing a throw-expression with no operand calls terminate()(15.5.1).

至于为什么编译器不能诊断这一点,需要一些非常复杂的流分析来做到这一点,我猜编译器作者C ++(和其他语言)充满了可能的错误,在理论上被编译器捕获,但实际上并不是这样。

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.

这篇关于为什么会抛出“无”导致程序终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆