异常处理的概念
在进行团队开发的过程中,可以通过对异常处理机制来降低产生错误的可能性,从而提高程序的可靠性。
仅仅用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;
}
转载自:黑凤梨の博客