c++中的异常处理机制

关于c++中的异常处理机制主要是try...catch语句,下面给出了一个除数为0的异常处理程序代码。

  • 基本语句代码详见下例
//hmtian
#include<iostream>

template<class T>
T div(T x, T y)
{
	if (y == 0)
	{
		throw y;
	}
	
	return x / y;
}

template<class T>
void test()
{
	try
	{
		div<int>(3, 0);
	}
	catch (T y)
	{
		std::cout << "Divisor cannot be" << y << std::endl;
	}
	catch (...)
	{
		std::cout << "unexpected";
	}
}

void test1() throw(int, float)//限定抛出异常类型
{
	try
	{
		div<float>(3.00, 0.00);
	}
	catch (float y)
	{
		std::cout << "Divisor cannot be" << y << std::endl;
	}
	catch (...)
	{
		std::cout << "unexpected";
	}
}

int main()
{
	test<int>();
	test1();
	system("pause");
}
  • 栈解旋
    异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反,这一过程称为栈的解旋(unwinding)。
#include<iostream>

template<class T>
class test
{
public:
	test(T a, T b) : x(a), y(b)
	{
		std::cout << "Constructor" << std::endl;
		std::cout << "result:" << div(x, y) << std::endl;
	}
	~test()
	{
		std::cout << "Destructor" << std::endl;
	}

	T div(T x, T y)
	{
		if (y == 0)
		{
			throw y;
		}
		return x / y;
	}
private:
	T x, y;
};

template<class T>
void divtest(T x, T y)
{
	try
	{
		test<T> t1(x, y), t2(x+3,y+2);
	}
	catch (	T y)
	{
		std::cout << "Divisor cannot be" << y << std::endl;
	}
}

template<class T>
void my_divtest(T x, T y) noexcept
{
	test<T>(x, y);
}

int main()
{
	divtest<int>(3,1);
	divtest<int>(3,0);
	//my_divtest<int>(3, 0);
	system("pause");
}

运行结果如下:
在这里插入图片描述

  • 关于noexpect的用法:

现在我们将上述main()函数中的注释去掉之后再次运行会有以下结果:
在这里插入图片描述
可以看到程序直接终止运行,如果被noexcept修饰的函数抛出了异常,编译器直接选择调用标准库里面的 std::terminate()直接终止程序,比throw()在处理异常的效率要高些,有效的防治了异常的扩散传播

如果你对自己的函数有自信觉得不会抛出异常,你可以使用noexpect,反之,如果程序终止了,那可能错误就出现在加了关键字noexpect的函数这里。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值