C++异常处理

异常处理的概念

在进行团队开发的过程中,可以通过对异常处理机制来降低产生错误的可能性,从而提高程序的可靠性。

仅仅用if语句的判断,并不能够将所有出现异常的可能性都包括,如果开发较大规模的程序,就会导致正常的逻辑代码和处理异常的代码混淆在一起,增加了程序维护的难度。

通过异常处理机制,在整个程序段发生异常后都不至于导致程序出错,而是将异常抛出。
案例一(除数为0):

#include <iostream>
using namespace std;

double fuc(double x, double y)
{
	if (y == 0)
	{
		throw y;//除数为0,抛出异常
	}
	return x / y;
}

int main()
{
	double res;
	//定义异常
	try
	{
		res = fuc(100 ,60);
		cout << "100/60的结果为:" << res << endl;
		res = fuc(100 , 0);
	}
	//捕获并处理异常
	catch (double)
	{
		cerr << "Error of dividing zero." << endl;
	}

	system("pause");
	return 0;
}

在这里插入图片描述
结果分析:
该例中,除数为0的异常,用throw语句来抛出异常,用try/catch语句来捕获,从而实现异常处理。

案例二(方程无实数根):

#include <iostream>
#include<math.h>
using namespace std;

double sqrt_delta(double d)
{
	if (d < 0)
	{
		throw 1;
	}
	return sqrt(d);
}
double delta(double a, double b, double c)
{
	double d = b * b - 4 * a * c;
	return sqrt_delta(d);
}


int main()
{
	double a, b, c;
	cout << "请输入a,b,c的值:" << endl;
	cin >> a >> b >> c;
	while (true)
	{
		try
		{
			double d = delta(a, b, c);
			cout << "x1:" << (d - b) / (2 * a)  << endl;
			cout << "x1:" << -(d + b) / (2 * a) << endl;
			break;
		}
		catch (int)
		{
			cout << "delta < 0,请重新输入a,b,c:";
			cin >> a >> b >> c;
		}
	}


	system("pause");
	return 0;
}

在这里插入图片描述
案例三(捕获多个异常):

#include <iostream>
using namespace std;

void fun(int x)
{
	try 
	{
		if (x == 1) throw 1;
		if (x == 2) throw 1.0;
		if (x == 3) throw 1;
	}
	catch (int)
	{
		cout << "catch an int in fun()" << endl;
	}
	catch (double)
	{
		cout << "catch an double in fun()" << endl;
	}
	cout << "texting exception in fun()" << endl;
}
void gun()
{
	try 
	{
		fun(1);
		//fun(2);
		//fun(3);
		//fun(4);
	}
	catch (char)
	{
		cout << "catch a char in gun()" << endl;
	}
	cout << "texting exception in gun()" << endl;
}
int main()
{
	gun();
	
	system("pause");
	return 0;
}

在这里插入图片描述
转载自:黑凤梨の博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值