一 异常处理一些相关的概念
1.C++异常处理遵循的其中一个逻辑:如果在执行一个函数中出现异常,可以不在本函数中立即处理,而是发送一个信息给上一级函数,它的上一级捕获后继续处理。如果上一级也无法处理,则可以逐级上送,直到主函数。如果主函数也无法处理则终止程序。
2.C++异常处理机制由三部分组成:检查(try),抛出(throw),捕获(catch)。
把需要检查的代码块放在try代码块中,throw用来当出现异常时发出一个异常信息,而catch用来捕获异常信息,就处理它。
3.异常处理语法:
throw语句的形式:
throw 表达式;
try-catch语句结构:
try
{
被检查的语句;
}
catch(异常信息类型[变量名])
{
进行异常处理语句:
}
一些说明:
1)如果catch子句中没有指定异常信息的类型,而是使用了删节号“...”,则表示可以捕获任何信息。
2)try-catch语句可以和throw语句不在同一个函数中。当throw抛出异常时,首先会去本函数中与之匹配的catch语句,本函数中没有,就会去上一级函数中寻找。
3)throw ;表示:我们不处理交给上一级处理。
二 异常处理一些相关的案例
案例一:
//给出三角形三条边a,b,c,求三角形的面积,异常出现在输入的三条边长可能无法构成三角形
#include<iostream>
using namespace std;
#include<cmath>
//求面积函数
double fact(double a,double b,double c)
{
double s = (a + b + c) / 2;
if (a+b<=c||a+c<=b||b+c<=a)
throw a;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
int main()
{
double a, b, c;
cin >> a >> b >> c;
try
{
while(a > 0 && b > 0 && c > 0)
{
cout << fact(a, b, c) << endl;
cin >> a >> b >> c;
}
}
catch (double)
{
cout << "所输入的三条边长无法构成三角形!" << endl;
}
cout<<"---ending--" << endl;
return 0;
}
案例二:
//求一元二次方程的解,如果没有实根,则输出警告。
#include<iostream>
using namespace std;
#include<cmath>
void fact(int a,int b,int c)
{
int s = b * b - 4*a * c;
double x1, x2;
if (s < 0)
throw s;
x1 = 1.0*(-b + sqrt(s)) / (2 * a);
x2 = 1.0*(-b - sqrt(s)) / (2 * a);
cout << x1 << endl;
cout << x2 << endl;
}
int main()
{
int a, b, c;
cin >> a >> b >> c;
try
{
while (true)
{
fact(a,b,c);
cin >> a >> b >> c;
}
}
catch (int)
{
cout << "此方程无实根!" << endl;
}
cout << "----ending----" << endl;
return 0;
}
案例三(自定义异常类):
#include<iostream>
using namespace std;
#include<string>
class CException
{
public:
string msg;
CException(string s) :msg(s) {}//构造函数,将s赋值给msg
};
double Devide(double x,double y)
{
if (y == 0)
throw CException("devided by zero");
cout << "in Devide" << endl;
return x / y;
}
int main()
{
double x, y;
cin >> x >> y;
try
{
while(true)
{
cout << Devide(x,y) << endl;
cin >> x >> y;
}
}
catch (CException e)
{
cout << e.msg << endl;
}
cout << "end Devide" << endl;
}