c++_狄泰总结06(异常处理)

C语言异常处理

本质:if…else…
缺陷:正常代码跟异常代码结合在一起,代码膨胀且不易阅读跟维护
在这里插入图片描述

案例1:除法函数divide(商为0)异常处理

缺点:a) divide(double a, double b, int* valid)为3个参数,不同于习惯(习惯是两个参数:除数和被除数)
b) 在使用前,通过对valid进行异常判断

#include <iostream>
#include <string>

using namespace std;

double divide(double a, double b, int* valid)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
        
        *valid = 1;
    }
    else
    {
        *valid = 0;
    }
    
    return ret;
}

int main(int argc, char *argv[])
{   
    int valid = 0;
    double r = divide(1, 0, &valid);
    
    if( valid )
    {
        cout << "r = " << r << endl;
    }
    else
    {
        cout << "Divided by zero..." << endl;
    }
    
    return 0;
}

案例2:采用setjump 跟longjump 对devide除法函数进行异常处理

优点:divide函数只采用了两个参数
缺点:
a)必须使用一个全局变量
b) 暴力跳转,破坏了程序结构的顺序执行原则,增加了代码的阅读复杂性,所以还是会使用案例1的异常处理方式

#include <iostream>
#include <string>
#include <csetjmp>

using namespace std;

static jmp_buf env;			//保存上下文信息

double divide(double a, double b)
{
    const double delta = 0.000000000000001;
    double ret = 0;
    
    if( !((-delta < b) && (b < delta)) )
    {
        ret = a / b;
    }
    else		//divide函数发现除数是0,于是会跳到else分支,执行longjmp,执行longjmp后会跳到setjmp(env),且返回值是1
    {
        longjmp(env, 1);
    }
    
    return ret;
}

int main(int argc, char *argv[])
{   
    if( setjmp(env) == 0 )	//从main函数开始执行,来到setjmp,会将上下文信息全部保存到env那里,由于一开始保存所以返回值为0,执行divide除法函数
    {
        double r = divide(1, 0);	
        
        cout << "r = " << r << endl;
    }
    else		//从longjmp返回  if( setjmp(env) == 0 ),由于返回值是1,执行else分支,输出Divided by zero...
    {
        cout << "Divided by zero..." << endl;
    }
    
    return 0;
}

C++异常处理

1)c++ 采用try catch 关键词进行异常处理 ,并由 throw抛出异常信息(try 中存放可能产生异常的代码)
2)try 中存放可能产生异常的代码,,throw抛出异常信息,并由上一层try catch进行异常处理
3)一个try可以由多个catch 对应 {不同的catch处理不同的异常情况}
3)throw 中可以抛出任何类型(包括自定义类类型)
=>throw 抛出的异常必须被catch处理,如果当前的函数try catch 能够处理则继续运行,否则函数返回到上一个调用函数,直到被处理为止,否则程序将停止执行
4)c++ 提供了实用异常类

在这里插入图片描述
异常处理原则
a)catch 中自上而下对异常信息进行严格匹配,不进行任何隐式转换
b)任何异常都只能catch 一次
c)catch 语句可以定义具体处理的异常类型
d) catch (…) 表示捕获任何异常,通常放在catch的最后面
e) throw 可以抛出类对象 ,类类型需要注意继承关系,子类继承父类,赋值兼容性原则也适用(子类可以当做父类来使用),因此 通常把父类catch 放在 子类catch的下面

问题:为什么需要在catch中抛出异常?
答:实际项目开发中,有可能会遇到 异常信息是由第三方提供的,代码无法修改的情况,而catch信息不太完整,需要重新解释
在这里插入图片描述

案例1:重新解释异常信息

/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: void func(int i)
    抛出异常的类型: int
                        -1 ==》 参数异常
                        -2 ==》 运行异常
                        -3 ==》 超时异常
*/
void func(int i)
{
    if( i < 0 )
    {
        throw -1;
    }
    
    if( i > 100 )
    {
        throw -2;
    }
    
    if( i == 11 )
    {
        throw -3;
    }
    
    cout << "Run func..." << endl;
}
void MyFunc(int i)
{
    try
    {
        func(i);
    }
    catch(int i)
    {
        switch(i)
        {
            case -1:	//在catch中抛出异常,重新解释异常信息
                throw "Invalid Parameter";
                break;
            case -2:
                throw "Runtime Exception";
                break;
            case -3:
                throw "Timeout Exception";
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    // Demo();
    
    try
    {
        MyFunc(11);
    }
    catch(const char* cs)
    {
        cout << "Exception Info: " << cs << endl;
    }
    
    return 0;
}

案例2:自定义类类型,重新解释并抛出的更多异常信息

class Base
{
};

class Exception : public Base		//自定义类类类型 ,提供第三方的信息 +重新解释的信息
{		//赋值兼容性原则也适用(子类可以当做父类来使用)
    int m_id;
    string m_desc;
public:
    Exception(int id, string desc)
    {
        m_id = id;
        m_desc = desc;
    }
    //这里有一个问题?为什么要加const? 加了后变成const函数,只能被const对象调用??
    //=>答 成员函数后面加const 只能读取成员函数,而不能修改
    int id() const	//由于成员是private,所以需要在public中提供成员函数获取信息
    {
        return m_id;
    }
    
    string description() const
    {
        return m_desc;
    }
};


/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: void func(int i)
    抛出异常的类型: int
                        -1 ==》 参数异常
                        -2 ==》 运行异常
                        -3 ==》 超时异常
*/
void func(int i)
{
    if( i < 0 )
    {
        throw -1;
    }
    
    if( i > 100 )
    {
        throw -2;
    }
    
    if( i == 11 )
    {
        throw -3;
    }
    
    cout << "Run func..." << endl;
}

void MyFunc(int i)
{
    try
    {
        func(i);
    }
    catch(int i)
    {
        switch(i)
        {
            case -1:	//Exception(-1, "Invalid Parameter")构造函数,抛出一个Exception 类对象
                throw Exception(-1, "Invalid Parameter");	
                break;
            case -2:
                throw Exception(-2, "Runtime Exception");
                break;
            case -3:
                throw Exception(-3, "Timeout Exception");
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    try
    {
        MyFunc(11);
    }
    catch(const Exception& e)	//由于赋值兼容原则(子类对象可以当做父类对象来使用),这里先catch子类
    {
        cout << "Exception Info: " << endl;
        cout << "   ID: " << e.id() << endl;
        cout << "   Description: " << e.description() << endl;
    }
    catch(const Base& e)
    {
        cout << "catch(const Base& e)" << endl;
    }
    
    return 0;
}

C++类型识别

C++类型识别分为静态类型和动态类型
静态类型是变量自身的类型,这种编译前可以知道的,
动态类型是指针或引用 所指向的实际对象的类型,这种编译的时候是无法确定的

C++ 提供关键字 typeid 进行类型识别**,返回信息存放在type_info类对象,typeid的参数不为空,为NULL则异常抛出,#include

用法:

#include <typeinfo>
	int i = 0;   
    const type_info& tiv = typeid(i);	//a)当参数为变量时,不存在虚函数表时,返回静态变量信息
    const type_info& tii = typeid(int); //a)当参数为类型时,返回静态变量信息
    
    cout << (tiv == tii) << endl;

注意点:
a)当参数为类型时,返回静态变量信息
b)当参数为变量时,先看变量里面是否存在虚函数表
不存在:返回静态信息
存在虚函数表 virtual: 返回动态类别信息
c) typeid 采用不同的编译器,返回的动态类别信息是不一样的

问1:为什么会有静态类型和动态类型的区别?
原因是由于 c++中的赋值兼容性原则
面向对象中可能出现下列问题:
基类指针 指向 子类对象
基类引用 成为子类对象的别名
Base* p = new Derived ();
Base& r = *p
静态类型 :Base 是我们期待的,程序是确定的
动态类型: Derrived => p 指针指向的 可能是父类对象 ,也可能是子类对象(赋值兼容性原则)
r 可能是 父类对象的引用 ,也有可能是子类对象的引用

怎么知道 p指针指向的是父类对象还是子类对象?=》引出问题2:C++如何获得动态类型*

案例1 )利用利用多态和虚函数判断具体动态识别是什么类型

要求:a) 基类定义虚函数返回具体的类型信息
b)每一个派生类都必须实现具体类型的相关函数
c)每个类中的类型虚函数都要不同的实现
缺点:
a)基类必须定义虚函数
b)每个派生类都要实现具体类型的相关函数,且要不同的实现=》这里不容易维护,且容易出错漏写
c) 派生类的类型名必须唯一

#include <iostream>
#include <string>

using namespace std;

class Base
{
public:
    virtual string type()	//基类定义虚函数
    {
        return "Base";
    }
};

class Derived : public Base
{
public:
    string type()		//子类多态实现,b)每一个派生类都必须实现具体类型的相关函数,这里返回类名,保证每个派生类都各不相同
    {
        return "Derived";
    }
    
    void printf()
    {
        cout << "I'm a Derived." << endl;
    }
};

class Child : public Base
{
public:
    string type()
    {
        return "Child";
    }
};

void test(Base* b)
{
    /* ΣЕքתۻ׽ʽ */
    // Derived* d = static_cast<Derived*>(b);
    
    if( b->type() == "Derived" )
    {
        Derived* d = static_cast<Derived*>(b);
        
        d->printf();
    }
    
    // cout << dynamic_cast<Derived*>(b) << endl;
}


int main(int argc, char *argv[])
{
    Base b;
    Derived d;
    Child c;
    
    test(&b);
    test(&d);
    test(&c);
    
    return 0;
}

案例2:用c++ 提供的typeid 获取具体动态类型

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

class Base
{
public:
    virtual ~Base()		//基类加virtual,用来验证typeid作用
    {
    }
};

class Derived : public Base
{
public:
    void printf()
    {
        cout << "I'm a Derived." << endl;
    }
};

void test(Base* b)
{
    const type_info& tb = typeid(*b);		//当参数为变量,存在虚函数表时
    
    cout << tb.name() << endl;
}

int main(int argc, char *argv[])
{
    int i = 0;
    
    const type_info& tiv = typeid(i);	//a)当参数为变量时,不存在虚函数表时,返回静态变量信息
    const type_info& tii = typeid(int); //a)当参数为类型时,返回静态变量信息
    
    cout << (tiv == tii) << endl;
    
    Base b;
    Derived d;
    
    test(&b);		当参数为变量,存在虚函数表时,返回动态信息
    test(&d);
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值