C++【异常】

一、传统的处理错误方式

C语言传统的处理错误的方式

传统的错误处理机制:

  1. 终止程序,如assert,缺陷:用户难以接受。如发生内存错误,除0错误时就会终止程序。
  2. 返回错误码,缺陷:需要程序员自己去查找对应的错误。如系统的很多库的接口函数都是通过把错误码放到errno中,表示错误
    实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误
    (比方说返回了一个-1,1,3,我们根本都不知道这是什么错误)

C++异常概念

异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。
throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。(抛出一个对象出来)
catch: 在您想要处理问题的地方,通过异常处理程序捕获异常.catch 关键字用于捕获异常,可以有多个catch进行捕获。
try: try 块中的代码标识将被激活的特定异常,它后面通常跟着一个或多个 catch 块。
如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。
使用 try/catch 语句的语法如下所示:

try
{
// 保护的标识代码
}catch( ExceptionName e1 )
{
// catch 块
}catch( ExceptionName e2 )
{
// catch 块
}catch( ExceptionName eN )
{
// catch 块
}

我们看一下如何捕获除0异常

#include <iostream>
using namespace std;

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
        //抛出的异常传给了我们下面的main函数中的catch
        //也就是传给了const char* ermsg
        throw "Division by zero condition!";
    else
        return ((double)a / (double)b);
}
void Func()
{
    int len, time;
    cin >> len >> time;
    cout << Division(len, time) << endl;
}

int main() {
    try{
        Func();
    }
    //正常执行的话,会跳过catch的执行,只执行try中的代码
    catch(const char* ermsg)
    {
        cout<<ermsg<<endl;
    }
    return 0;
}

在这里插入图片描述

二、异常的使用

1.异常的抛出和捕获

异常的抛出和匹配原则

  1. 异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码。
  2. 选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。
  3. 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回)
  4. catch(…)可以捕获任意类型的异常,问题是不知道异常错误是什么。
  5. 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象,使用基类捕获,这个在实际中非常实用。
    在函数调用链中异常栈展开匹配原则
  6. 首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch的地方进行处理。
  7. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
  8. 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(…)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。
  9. 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。

在这里插入图片描述

有多个捕获的话,走离捕获更近的那一个,也就是我们这里的func函数中的捕获,不走main函数中的那一个,但是这里要求类型必须要是匹配的!

#include <iostream>
using namespace std;

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
        //抛出的异常传给了我们下面的main函数中的catch
        //也就是传给了const char* ermsg
        throw "Division by zero condition!";
    else
        return ((double)a / (double)b);
}
void Func()
{
    //有多个捕获的话,走离捕获更近的那一个,也就是我们这里的func函数中的捕获,不走main函数中的那一个
    //但是这里要求类型必须要是匹配的!
    try{
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;
        
    }catch(const char* ermsg)
    {
        cout<<ermsg<<endl;
    }
    cout<<"Func()"<<endl;
}

int main() {
    try {
        Func();
    }
    catch(const char* ermsg)
    {
        cout<<ermsg<<endl;
    }
    catch(int errid)
    {
        cout<<errid<<endl;
    }
    return 0;
}

在这里插入图片描述

如果一层层的异常捕获都没有匹配上,那么程序就会报错,程序终止!
这里无论是Func中的还是main函数中的捕获异常都是捕获一个int类型的异常值,但是我们抛出异常是抛出一个string,那么都匹配补上的话,我们的程序就会报错。

#include <iostream>
using namespace std;

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
        //抛出的异常传给了我们下面的main函数中的catch
        //也就是传给了const char* ermsg
        throw "Division by zero condition!";
    else
        return ((double)a / (double)b);
}
void Func()
{
    //有多个捕获的话,走离捕获更近的那一个,也就是我们这里的func函数中的捕获,不走main函数中的那一个
    //但是这里要求类型必须要是匹配的!
    try{
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;

    }catch(int errid)
    {
        cout<<errid<<endl;
    }
    cout<<"Func()"<<endl;
}

int main() {
    try {
        Func();
    }
    catch(int errid)
    {
        cout<<errid<<endl;
    }
    return 0;
}

在这里插入图片描述

2.捕获任意类型的异常"…"

如果所有类型的异常都匹配不上的话,我们可以写一个catch(…)来将所有匹配不上的异常给捕获,用来防止出现未捕获的异常时,程序终止。

#include <iostream>
using namespace std;

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
        //抛出的异常传给了我们下面的main函数中的catch
        //也就是传给了const char* ermsg
        throw "Division by zero condition!";
    else
        return ((double)a / (double)b);
}
void Func()
{
    //有多个捕获的话,走离捕获更近的那一个,也就是我们这里的func函数中的捕获,不走main函数中的那一个
    //但是这里要求类型必须要是匹配的!
    try{
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;

    }catch(int errid)
    {
        cout<<errid<<endl;
    }
    cout<<"Func()"<<endl;
}

int main() {
    try {
        Func();
    }
    catch(int errid)
    {
        cout<<errid<<endl;
    }
    catch(...)
    {
        //我不知道我捕获了什么异常
        cout<<"未知异常"<<endl;
    }
    return 0;
}

在这里插入图片描述

加上了catch(…)可以防止我们的程序因为异常而崩溃

#include <iostream>
using namespace std;

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
        throw "Division by zero condition!";
    else
        return ((double)a / (double)b);
}
void Func()
{
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;
}

int main() {
    while(1)
    {
        try {
            Func();
        }
        catch(int errid)
        {
            cout<<errid<<endl;
        }
        catch(...)
        {
            //我不知道我捕获了什么异常
            cout<<"未知异常"<<endl;
        }
    }
    return 0;
}

在这里插入图片描述

然后我们可以封装一下我们的exception

#include <iostream>
using namespace std;
class Exception
{
public:
    Exception(const string& errmsg, int id)
            :_errmsg(errmsg)
            ,_id(id)
    {}
    virtual string what() const
    {
        return _errmsg;
    }
protected:
    string _errmsg;
    int _id;
};

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0) {//抛出的异常传给了我们下面的main函数中的catch
        //也就是传给了const char* ermsg
        Exception e("除0错误", 1);
        //传值返回
        throw e;
    }
    else {
        return ((double) a / (double) b);
    }
}
void Func1()
{
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;
}

int main() {
    while(1)
    {
        try {
            Func1();
        }
        catch(const Exception&e)
        {
            cout<<e.what()<<endl;
        }
        catch(...)
        {
            //我不知道我捕获了什么异常
            cout<<"未知异常"<<endl;
        }
    }
    return 0;
}

在这里插入图片描述

1、抛异常可以抛任意类型的对象
2、捕获的时候不同的类型需要有不同的捕获方式,然后进行不同的处理
(比方说服务器上就可以将异常记录到日志中)

异常标准化

虽然说抛异常可以任意抛,但是我们的异常的抛出最好是要有一定的规范的。
可以抛出的派生类对象,使用基类捕获,这个在实际中非常实用。
库里面有一个exception的基类,也可以抛派生类的对象,用基类捕获。

#include <iostream>
#include<vector>
#include <thread>
#include <time.h>
#include <unistd.h>
#include <stack>

using namespace std;
// 服务器开发中通常使用的异常继承体系
//基类
class Exception
{
public:
    //构造的时候需要将错误码和错误信息描述清楚
    Exception(const string& errmsg, int id)
            :_errmsg(errmsg)
            ,_id(id)
    {}
    //使用多态
    //what函数用来返回错误信息
    virtual string what() const
    {
        return _errmsg;
    }
    //返回错误码
    int getid()
    {
        return _id;
    }
protected:
    string _errmsg; //错误信息
    //错误码
    int _id;
};


//如果是sql出错了
class SqlException : public Exception
{
public:
    SqlException(const string& errmsg, int id, const string& sql)
            :Exception(errmsg, id)
            , _sql(sql)
    {}
    virtual string what() const
    {
        string str = "SqlException:";
        str += _errmsg;
        str += "->";
        str += _sql;
        return str;
    }
private:
    const string _sql;
};


//如果是缓存出错了
class CacheException : public Exception
{
public:
    CacheException(const string& errmsg, int id)
            :Exception(errmsg, id)
    {}
    virtual string what() const
    {
        string str = "CacheException:";
        str += _errmsg;
        return str;
    }

protected:
    //查堆栈信息
    //stack<string> _stPath;
};

//如果是网络服务出错了
class HttpServerException : public Exception
{
public:
    HttpServerException(const string& errmsg, int id, const string& type)
            :Exception(errmsg, id)
            , _type(type)
    {}
    virtual string what() const
    {
        string str = "HttpServerException:";
        str += _type;
        str += ":";
        str += _errmsg;
        return str;
    }
private:
    const string _type;
};
void SQLMgr()
{
    //模拟随机错误
    srand(time(0));
    if (rand() % 7 == 0)
    {
        throw SqlException("权限不足", 100, "select * from name = '张三'");
    }
    //假设成功了。
    cout<<"请求成功"<<endl;
}

void CacheMgr()
{
    //模拟随机错误
    srand(time(0));
    if (rand() % 5 == 0)
    {
        throw CacheException("权限不足", 200);
    }
    else if (rand() % 6 == 0)
    {
        throw CacheException("数据不存在", 201);
    }
    //检查数据库错误
    SQLMgr();
}

void HttpServer()
{
// 模拟随机错误
    srand(time(0));
    if (rand() % 3 == 0)
    {
        //get错误
        throw HttpServerException("请求资源不存在", 100, "get");
    }
    else if (rand() % 4 == 0)
    {
        //post错误
        throw HttpServerException("权限不足", 101, "post");
    }
    //网络层如果没出问题,就去缓存层检查
    CacheMgr();
}

//PC客户端
//APP
//web
int main()
{
    while (1)
    {
//        this_thread::sleep_for(chrono::seconds(1));
        sleep(1);
        try{
            HttpServer();
        }
        //捕获基本类,然后捕获抛出的子类
        catch (const Exception& e) // 这里捕获父类对象就可以
        {
            // 多态
            cout << e.what() << endl;
        }
        //守住程序健壮性的底线
        catch (...)
        {
            cout << "Unkown Exception" << endl;
        }
    }
    return 0;
}

异常的重新抛出

有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。
比方说发送数据,没有发送成功,我还想重试几次。

#include <iostream>
#include<vector>
#include <thread>
#include <time.h>
#include <unistd.h>
#include <stack>

using namespace std;
// 服务器开发中通常使用的异常继承体系
//基类
class Exception
{
public:
    //构造的时候需要将错误码和错误信息描述清楚
    Exception(const string& errmsg, int id)
            :_errmsg(errmsg)
            ,_id(id)
    {}
    //使用多态
    //what函数用来返回错误信息
    virtual string what() const
    {
        return _errmsg;
    }
    //返回错误码
    int getid() const
    {
        return _id;
    }
protected:
    string _errmsg; //错误信息
    //错误码
    int _id;
};


//如果是网络服务出错了
class HttpServerException : public Exception
{
public:
    HttpServerException(const string& errmsg, int id, const string& type)
            :Exception(errmsg, id)
            , _type(type)
    {}
    virtual string what() const
    {
        string str = "HttpServerException:";
        str += _type;
        str += ":";
        str += _errmsg;
        return str;
    }
private:
    const string _type;
};

void SendMSG(const string message)
{
// 模拟随机错误
    srand(time(0));
    if (rand() % 3 == 0) {
        //出现网络错误,重试三次
        throw HttpServerException("网络错误", 100, "get");
    } else if (rand() % 4 == 0) {
        //出现权限错误直接抛出异常
        throw HttpServerException("权限不足", 101, "post");
    }
    cout<<"发送成功:"<<message<<endl;

}


void HttpServer()
{
    //要求出现网络错误,重试3次
    string str;
//    cin>>str;
    str="啊哈哈哈,鸡汤来喽,哈哈哈";
    //尝试次数
    int n=3;
    while(n--)
    {
        try {
            SendMSG(str);
            //不抛异常,正常结束,跳出while循环
            //没有发生异常
            break;
            //拦截错误
        }catch (const Exception &e){
            //知道是网络错误且重试已经超过了三次
            if(e.getid()==100 && n >0) {
                //重试
                continue;
            }
            else{
                //如果是权限错误的话,就直接抛出来
                //我们需要将异常重新抛出
                throw e;
            }
        }
    }



}
//PC客户端
//APP
//web
int main()
{
    while (1)
    {
        sleep(1);
        try{
            HttpServer();
        }
        //捕获基本类,然后捕获抛出的子类
        catch (const Exception& e) // 这里捕获父类对象就可以
        {
            // 多态
            cout << e.what() << endl;
            //记录日志
        }
        //守住程序健壮性的底线
        catch (...)
        {
            cout << "Unkown Exception" << endl;
        }
    }
    return 0;
}

在这里插入图片描述

另一种情况,就是如果你抛了异常,跳转到了catch,但是我们原来代码中的对象空间并没有释放,就会导致内存泄漏问题。
我们需要将对象的空间释放!

double Division(int a, int b)
{
// 当b == 0时抛出异常
    if (b == 0)
    {
        throw "Division by zero condition!";
    }
    return (double)a / (double)b;
}
void Func()
{
// 这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
// 所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再
// 重新抛出去。
    int* array = new int[10];
    try {
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;
    }
    catch (...)
    {
        cout << "delete []" << array << endl;
        //捕获了异常之后,还需要将我们的对象的空间给释放。
        delete[] array;
        //我们的异常还需要继续抛出
        throw;
    }
// ...
    cout << "delete []" << array << endl;
    delete[] array;
}
int main()
{
    try
    {
        Func();
    }
    catch (const char* errmsg)
    {
        cout << errmsg << endl;
    }
    return 0;
}

异常的隐患

double Division(int a, int b)
{
    if (b == 0)
    {
        throw "Division by zero condition!";
    }
    return (double)a / (double)b;
}
void Func()
{
// 隐患是第一个成功,后面的几个失败
// 那么我们的
    int* array1 = new int[10];
    int* array2 = nullptr;
    int* array3 = nullptr;
    int* array4 = nullptr;
    int* array5 = nullptr;
    try {
        int* array2 = new int[10];
        int* array3 = new int[10];
        int* array4 = new int[10];
        int* array5 = new int[10];
        int len, time;
        cin >> len >> time;
        cout << Division(len, time) << endl;
    }
    catch (...)
    {
        delete[] array1;
        delete[] array2;
        delete[] array3;
        delete[] array4;
        delete[] array5;
        //我们的异常还需要继续抛出
        throw;
    }
}
int main()
{
    try
    {
        Func();
    }
    catch (const char* errmsg)
    {
        cout << errmsg << endl;
    }
    return 0;
}

异常安全

构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化。
析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)
C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题。

异常规范

  1. 异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的后面接throw(类型),列出这个函数可能抛掷的所有异常类型。
  2. 函数的后面接throw(),表示函数不抛异常。
  3. 若无异常接口声明,则此函数可以抛掷任何类型的异常。
//C++98
// 这里表示这个函数会抛出A/B/C/D中的某种类型的异常
void fun() throw(A,B,C,D);
// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);
// 这里表示这个函数不会抛出异常
void* operator delete (std::size_t size, void* ptr) throw();

// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;

C++标准库的异常体系
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、异常的优缺点

异常的优点

  1. 异常对象定义好了,相比错误码的方式可以清晰准确的展示出错误的各种信息,甚至可以包含堆栈调用的信息,这样可以帮助更好的定位程序的bug。
  2. 返回错误码的传统方式有个很大的问题就是,在函数调用链中,深层的函数返回了错误,那么我们得层层返回错误,最外层才能拿到错误,具体看下面的详细解释。
    在这里插入图片描述
  3. 很多的第三方库都包含异常,比如boost、gtest、gmock等等常用的库,那么我们使用它们也需要使用异常。
  4. 部分函数使用异常更好处理,比如构造函数没有返回值,不方便使用错误码方式处理。比如T& operator[](size_t pos)这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误。

异常的缺点

  1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会导致我们跟踪调试时以及分析程序时,比较困难。
  2. 异常会有一些性能的开销。当然在现代硬件速度很快的情况下,这个影响基本忽略不计。
  3. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常安全问题。这个需要使用RAII来处理资源的管理问题。学习成本较高。
  4. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。
  5. 异常尽量规范使用,否则后果不堪设想,随意抛异常,外层捕获的用户苦不堪言。所以异常规范有两点:一、抛出异常类型都继承自一个基类。二、函数是否抛异常、抛什么异常,都使用 func() throw();的方式规范化。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桜キャンドル淵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值