【C++进阶】异常详解

76 阅读6分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第N天,点击查看活动详情 ✨ 1. C语言传统的处理错误的方式 传统的错误处理机制:

终止程序,如assert,缺陷:用户难以接受。如发生内存错误,除0错误时就会终止程序。 返回错误码,缺陷:需要程序员自己去查找对应的错误。如系统的很多库的接口函数都是通过把错误码放到errno中,表示错误 C 标准库中setjmp和longjmp组合。这个不是很常用 实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误。 实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误。

int test(){ int a = 0; int b = 0; cin >> a >> b; if (b == 0){

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 程序没有终止

✨ 2. 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 块 }

1 2 3 4 5 6 7 8 9 10 11 12 ✨ 3. 异常的使用 🌟 3.1 异常的抛出和捕获 异常的抛出和匹配原则:

异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码。 被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回) catch(…)可以捕获任意类型的异常,问题是不知道异常错误是什么。 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象,使用基类捕获,这个在实际中非常实用。 在函数调用链中异常栈展开匹配原则

首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch的地方进行处理。 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的 catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(…)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。

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() { try { Func(); } catch (const char* errmsg) { cout << errmsg << endl; } catch(...){ cout<<"unkown exception"<<endl; }

return 0; 

}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 按照函数调用链,一层一层往外找,直到找到匹配的catch块,直接跳到匹配的catch块执行,执行完catch,会继续往catch块后面的语句执行。相当于没有找到匹配的函数栈帧被释放了。

🌟 3.2 异常的重新抛出 有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,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; 

}

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 🌟 3.3 异常安全 构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化

析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)

C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题。

有两种解决办法:

将异常捕获,释放资源后,将锁重新抛出。 使用RAII的思想解决。定义一个类封装,管理资源。当要使用时实例化一个类对象,将资源传入,当退出函数,调用对象析构函数,释放资源。 🌟 3.4 异常规范 异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的后面接throw(类型),列出这个函数可能抛掷的所有异常类型。 函数的后面接throw(),表示函数不抛异常。 若无异常接口声明,则此函数可以抛掷任何类型的异常。 // 这里表示这个函数会抛出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 new (std::size_t size, void* ptr) throw();

1 2 3 4 5 6 7 8 9 10 ✨ 4. 自定义异常体系 实际使用中很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者基本就没办法玩了,所以实际中都会定义一套继承的规范体系。这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了

// 服务器开发中通常使用的异常继承体系 class Exception { public: Exception(const string& errmsg, int id) :_errmsg(errmsg) ,_id(id) {} virtual string what() const { return _errmsg; } protected: string _errmsg; int _id; };

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

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 = '张三'"); } //throw "xxxxxx"; }

void CacheMgr() { srand(time(0)); if (rand() % 5 == 0) { throw CacheException("权限不足", 100); } else if (rand() % 6 == 0) { throw CacheException("数据不存在", 101); } SQLMgr(); }

void HttpServer() { // ... srand(time(0)); if (rand() % 3 == 0) { throw HttpServerException("请求资源不存在", 100, "get"); } else if (rand() % 4 == 0) { throw HttpServerException("权限不足", 101, "post"); } CacheMgr(); }

int main() { while (1) { this_thread::sleep_for(chrono::seconds(1)); try{ HttpServer(); } catch (const Exception& e) // 这里捕获父类对象就可以 { // 多态 cout << e.what() << endl; } catch (...) { cout << "Unkown Exception" << endl; } } return 0; }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 ✨ 5. C++标准库的异常体系 C++ 提供了一系列标准的异常,定义在 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:

说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一样自己定义一套异常继承体系。因为C++标准库设计的不够好用。