如何实现一个异常处理机制?

在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;

}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值