在C语言阶段,对于异常处理,我们是这样解决的:
但是,对于错误类型的描述却是很少,我们无法立即判断出错误的类型。
不过,在C++中我们可以后将其信息封装成为一个抽象基类,然后继承,对错误进行分类,然后利用多态的特性,对其错误进行准确的描述:
#include<iostream>
#include<string>
using namespace std;
//实现一个异常处理机制
//要实现多态->进行错误类型选择
//异常基类
class Exception
{
public:
Exception(int errID, string errCode)
:_errID(errID)
, _errCode(errCode)
{}
virtual void What()const=0;//纯虚函数, 不是纯虚函数就需要进行定义
protected:
int _errID;
string _errCode;
};
//数据库类
class DBException:public Exception
{
public:
DBException(int errID,string errCode)
:Exception( errID,errCode)
{
}
virtual void What()const
{
cout << "错误码:" <<_errID << endl;
cout << "描述符:" << _errCode << endl;
}
};
//网络类
class NetException:public Exception
{
public:
NetException(int errID, string errCode)
:Exception(errID,errCode)
{}
virtual void What() const
{
cout << "错误码:" << _errID << endl;
cout << "描述符:" << _errCode << endl;
}
};
void FunTest1()
{
DBException db(1,"数据插入失败");
throw db;
}
void FunTest2()
{
NetException ne(2, "网络连接错误");
throw ne;
}
int main()
{
try
{
FunTest1();
FunTest2();
}
catch (const Exception&e)
{
cout << typeid(e).name() << endl;
e.What();
}
catch (...)
{
cout << "未知异常!" << endl;
}
return 0;
}