定义异常类处理异常
- 类似上一个博客中的例子
- 输入一个学生的考试总分及科目数,计算并输出该学生的平均分。通过定义异常类的方式来处理除数为0和输入为负的异常。
#include <iostream>
using namespace std;
//定义除数为0异常类
class ZeroException{
private:
char* msg;
public:
ZeroException(char* str){ msg=str; }
char* show(){ return msg; }
};
//定义总分或科目数为负数异常类
class NegativeException{
private:
char* msg;
public:
NegativeException(char* str)
{
msg=str;
}
char* show()
{
return msg;
}
};
float div(float score,int n)
{
if(n==0) //抛出0异常
{
//抛出异常并调用了构造函数,初始化msg中内容
throw ZeroException("error:科目数为0");
}
if(n<0||score<0) //抛出输入为负异常
{
throw NegativeException("error:总分或科目数为负");
}
return score/n;
}
int main()
{
float score,result;
int n;
cout<<"输入总分和科目数:\n";
while(cin>>score>>n)
{
try
{
result=div(score,n);
cout<<"平均分:"<<result<<endl;
}
catch(ZeroException a) //捕获除数为0异常
//这里说明类型的同时也声明了类的实例对象a
{
//a对象的内容与抛出异常时的初始化值同步一致
cout<<a.show()<<endl;
}
catch(NegativeException b)
{
cout<<b.show()<<endl;
}
}
return 0;
}
运行结果:
异常类的派生
- 一个异常基类也可以派生出各种异常类。如果一个catch语句能够捕获基类的异常,那么它也可以捕获其派生类的异常。
- 如果捕获基类异常的catch语句在前,则捕获其派生类异常的catch语句就会失效,因此,应该注意正确安排catch语句的顺序。在一般情况下,将处理基类异常的catch语句放在处理其派生类异常的catch语句之后。(基类是派生类的基础,若放在派生类的前面,根据catch匹配对应类型的特性,派生类当然会被屏蔽掉)