首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【C++】异常

【C++】异常

作者头像
用户11290673
发布2025-02-10 14:15:02
发布2025-02-10 14:15:02
3050
举报
文章被收录于专栏:学习学习

1.异常的概念及使用

1.1异常的概念

异常处理机制允许程序中独⽴开发的部分能够在运⾏时就出现的问题进⾏通信并做出相应的处理,

异常使得我们能够将问题的检测与解决问题的过程分开,程序的⼀部分负责检测问题的出现,然后

解决问题的任务传递给程序的另⼀部分,检测环节⽆须知道问题的处理模块的所有细节。

C语⾔主要通过错误码的形式处理错误,错误码本质就是对错误信息进⾏分类编号,拿到错误码以

后还要去查询错误信息,⽐较⿇烦。异常时抛出⼀个对象,这个对象可以函数更全⾯的各种信息。

1.2异常的抛出和捕获

程序出现问题时,我们通过抛出(throw)⼀个对象来引发⼀个异常,该对象的类型以及当前的调⽤

链决定了应该由哪个catch的处理代码来处理该异常。

被选中的处理代码是调⽤链中与该对象类型匹配且离抛出异常位置最近的那⼀个。根据抛出对象的

类型和内容,程序的抛出异常部分告知异常处理部分到底发⽣了什么错误。

当throw执⾏时,throw后⾯的语句将不再被执⾏。程序的执⾏从throw位置跳到与之匹配的catch

模块,catch可能是同⼀函数中的⼀个局部的catch,也可能是调⽤链中另⼀个函数中的catch,控

制权从throw位置转移到了catch位置。这⾥还有两个重要的含义:1、沿着调⽤链的函数可能提早

退出。2、⼀旦程序开始执⾏异常处理程序,沿着调⽤链创建的对象都将销毁。

抛出异常对象后,会⽣成⼀个异常对象的拷⻉,因为抛出的异常对象可能是⼀个局部对象,所以会

⽣成⼀个拷⻉对象,这个拷⻉的对象会在catch⼦句后销毁。(这⾥的处理类似于函数的传值返

回)

1.3栈展开

抛出异常后,程序暂停当前函数的执⾏,开始寻找与之匹配的catch⼦句,⾸先检查throw本⾝是否

在try块内部,如果在则查找匹配的catch语句,如果有匹配的,则跳到catch的地⽅进⾏处理。

如果当前函数中没有try/catch⼦句,或者有try/catch⼦句但是类型不匹配,则退出当前函数,继续

在外层调⽤函数链中查找,上述查找的catch过程被称为栈展开。

如果到达main函数,依旧没有找到匹配的catch⼦句,程序会调⽤标准库的 terminate 函数终⽌

程序。

如果找到匹配的catch⼦句处理后,catch⼦句代码会继续执⾏。

double Divide ( int a, int b) { try { // b == 0 时抛出异常 if (b == 0 ) { string s ( "Divide by zero condition!" ); throw s; } else { return (( double )a / ( double )b); } } catch ( int errid) { cout << errid << endl; } return 0 ; } void Func () { int len, time; cin >> len >> time; try { cout << Divide (len, time) << endl; } catch ( const char * errmsg) { cout << errmsg << endl; } cout <<__FUNCTION__<< ":" << __LINE__ << " ⾏执⾏ " << endl; } int main () { while ( 1 ) { try { Func (); } catch ( const string& errmsg) { cout << errmsg << endl; } } return 0 ; }

1.4查找匹配的处理代码

⼀般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配的,就选择离他位置更近的

那个。

但是也有⼀些例外,允许从⾮常量向常量的类型转换,也就是权限缩⼩;允许数组转换成指向数组

元素类型的指针,函数被转换成指向函数的指针;允许从派⽣类向基类类型的转换,这个点⾮常实

⽤,实际中继承体系基本都是⽤这个⽅式设计的。

如果到main函数,异常仍旧没有被匹配就会终⽌程序,不是发⽣严重错误的情况下,我们是不期望程序终⽌的,所以⼀般main函数中最后都会使⽤catch(...),它可以捕获任意类型的异常,但是是

不知道异常错误是什么。

1 # include <thread> 2 3 // ⼀般⼤型项⽬程序才会使⽤异常,下⾯我们模拟设计⼀个服务的⼏个模块 4 // 每个模块的继承都是 Exception 的派⽣类,每个模块可以添加⾃⼰的数据 5 // 最后捕获时,我们捕获基类就可以 6 class Exception 7 { 8 public : 9 Exception ( const string& errmsg, int id) 10 :_errmsg(errmsg) 11 , _id(id) 12 {} 13 14 virtual string what () const 15 { 16 return _errmsg; 17 } 18 19 int getid () const 20 { 21 return _id; 22 } 23 24 protected : 25 string _errmsg; 26 int _id; 27 }; 28 29 class SqlException : public Exception 30 { 31 public : 32 SqlException ( const string& errmsg, int id, const string& sql) 33 : Exception (errmsg, id) 34 , _sql(sql) 35 {} 36 37 virtual string what () const 38 { 39 string str = "SqlException:" ; 40 str += _errmsg; 41 str += "->" ; 42 str += _sql; 43 return str; 44 } 45 private : 46 const string _sql; 47 }; 48 49 class CacheException : public Exception 50 { 51 public : 52 CacheException ( const string& errmsg, int id) 53 : Exception (errmsg, id) 54 {} 55 56 virtual string what () const 57 { 58 string str = "CacheException:" ; 59 str += _errmsg; 60 return str; 61 } 62 }; 63 64 class HttpException : public Exception 65 { 66 public : 67 HttpException ( const string& errmsg, int id, const string& type) 68 : Exception (errmsg, id) 69 , _type(type) 70 {} 71 72 virtual string what () const 73 { 74 string str = "HttpException:" ; 75 str += _type; 76 str += ":" ; 77 str += _errmsg; 78 return str; 79 } 80 81 private : 82 const string _type; 83 }; 84 85 void SQLMgr () 86 { 87 if ( rand () % 7 == 0 ) 88 { 89 throw SqlException ( " 权限不⾜ " , 100 , "select * from name = ' 张三 '" ); 90 } 91 else 92 { 93 cout << "SQLMgr 调⽤成功 " << endl; 94 } 95 } 96 97 void CacheMgr () 98 { 99 if ( rand () % 5 == 0 ) 100 { 101 throw CacheException ( " 权限不⾜ " , 100 ); 102 } 103 else if ( rand () % 6 == 0 ) 104 { 105 throw CacheException ( " 数据不存在 " , 101 ); 106 } 107 else 108 { 109 cout << "CacheMgr 调⽤成功 " << endl; 110 } 111 112 SQLMgr (); 113 } 114 115 void HttpServer () 116 { 117 if ( rand () % 3 == 0 ) 118 { 119 throw HttpException ( " 请求资源不存在 " , 100 , "get" ); 120 } 121 else if ( rand () % 4 == 0 ) 122 { 123 throw HttpException ( " 权限不⾜ " , 101 , "post" ); 124 } 125 else 126 { 127 cout << "HttpServer 调⽤成功 " << endl; 128 } 129 130 CacheMgr (); 131 } 132 133 134 int main () 135 { 136 srand ( time ( 0 )); 137 138 while ( 1 ) 139 { 140 this_thread:: sleep_for (chrono:: seconds ( 1 )); 141 142 try 143 { 144 HttpServer (); 145 } 146 catch ( const Exception& e) // 这⾥捕获基类,基类对象和派⽣类对象都可以被 捕获 147 { 148 cout << e. what () << endl; 149 } 150 catch (...) 151 { 152 cout << "Unkown Exception" << endl; 153 } 154 } 155 156 return 0 ; 157 }

1.5异常重新抛出

有时catch到⼀个异常对象后,需要对错误进⾏分类,其中的某种异常错误需要进⾏特殊的处理,其他错误则重新抛出异常给外层调⽤链处理。捕获异常后需要重新抛出,直接 throw; 就可以把捕获的对象直接抛出。

1 // 下⾯程序模拟展⽰了聊天时发送消息,发送失败补货异常,但是可能在 2 // 电梯地下室等场景⼿机信号不好,则需要多次尝试,如果多次尝试都发 3 // 送不出去,则就需要捕获异常再重新抛出,其次如果不是⽹络差导致的 4 // 错误,捕获后也要重新抛出。 5 void _SeedMsg( const string& s) 6 { 7 if ( rand () % 2 == 0 ) 8 { 9 throw HttpException ( " ⽹络不稳定,发送失败 " , 102 , "put" ); 10 } 11 else if ( rand () % 7 == 0 ) 12 { 13 throw HttpException ( " 你已经不是对象的好友,发送失败 " , 103 , "put" ); 14 } 15 else 16 { 17 cout << " 发送成功 " << endl; 18 } 19 } 20 21 void SendMsg ( const string& s) 22 { 23 // 发送消息失败,则再重试 3 24 for ( size_t i = 0 ; i < 4 ; i++) 25 { 26 try 27 { 28 _SeedMsg(s); 29 break ; 30 } 31 catch ( const Exception& e) 32 { 33 // 捕获异常, if 中是 102 号错误,⽹络不稳定,则重新发送 34 // 捕获异常, else 中不是 102 号错误,则将异常重新抛出 35 36 if (e. getid () == 102 ) 37 { 38 // 重试三次以后否失败了,则说明⽹络太差了,重新抛出异常 39 if (i == 3 ) 40 throw ; 41 42 cout << " 开始第 " << i + 1 << " 重试 " << endl; 43 } 44 else 45 { 46 throw ; 47 } 48 } 49 } 50 } 51 52 int main () 53 { 54 srand ( time ( 0 )); 55 56 string str; 57 while (cin >> str) 58 { 59 try 60 { 61 SendMsg (str); 62 } 63 catch ( const Exception& e) 64 { 65 cout << e. what () << endl << endl; 66 } 67 catch (...) 68 { 69 cout << "Unkown Exception" << endl; } 70} 71return 0 ; 72}

1.6异常安全问题

异常抛出后,后⾯的代码就不再执⾏,前⾯申请了资源(内存、锁等),后⾯进⾏释放,但是中间可

能会抛异常就会导致资源没有释放,这⾥由于异常就引发了资源泄漏,产⽣安全性的问题。中间我

们需要捕获异常,释放资源后⾯再重新抛出,当然后⾯智能指针章节讲的RAII⽅式解决这种问题是

更好的。

其次析构函数中,如果抛出异常也要谨慎处理,⽐如析构函数要释放10个资源,释放到第5个时抛

出异常,则也需要捕获处理,否则后⾯的5个资源就没释放,也资源泄漏了。《Effctive C++》第8

个条款也专⻔讲了这个问题,别让异常逃离析构函数。

double Divide ( 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 << Divide (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; } catch ( const exception& e) { cout << e. what () << endl; } catch (...) { cout << "Unkown Exception" << endl; } return 0 ; }

1.7异常规范

对于⽤⼾和编译器⽽⾔,预先知道某个程序会不会抛出异常⼤有裨益,知道某个函数是否会抛出异

常有助于简化调⽤函数的代码。

C++98中函数参数列表的后⾯接throw(),表⽰函数不抛异常,函数参数列表的后⾯接throw(类型1,

类型2...)表⽰可能会抛出多种类型的异常,可能会抛出的类型⽤逗号分割。

C++98的⽅式这种⽅式过于复杂,实践中并不好⽤,C++11中进⾏了简化,函数参数列表后⾯加

noexcept 表⽰不会抛出异常,啥都不加表⽰可能会抛出异常。

编译器并不会在编译时检查noexcept,也就是说如果⼀个函数⽤noexcept修饰了,但是同时⼜包

含了throw语句或者调⽤的函数可能会抛出异常,编译器还是会顺利编译通过的(有些编译器可能会

报个警告)。但是⼀个声明了noexcept的函数抛出了异常,程序会调⽤ terminate 终⽌程序。

noexcept(expression)还可以作为⼀个运算符去检测⼀个表达式是否会抛出异常,可能会则返回

false,不会就返回true。

// C++98 // 这⾥表⽰这个函数只会抛出 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 size_type size () const noexcept ; iterator begin () noexcept ; const_iterator begin () const noexcept ; double Divide ( int a, int b) noexcept { // b == 0 时抛出异常 if (b == 0 ) { throw "Division by zero condition!" ; } return ( double )a / ( double )b; } int main () { try { int len, time; cin >> len >> time; cout << Divide (len, time) << endl; } catch ( const char * errmsg) { cout << errmsg << endl; } catch (...) { cout << "Unkown Exception" << endl; } int i = 0 ; cout << noexcept ( Divide ( 1 , 2 )) << endl; cout << noexcept ( Divide ( 1 , 0 )) << endl; cout << noexcept (++i) << endl; return 0 ; }


2.标准库的异常

exception - C++ Reference

C++标准库也定义了⼀套⾃⼰的⼀套异常继承体系库,基类是exception,所以我们⽇常写程序,需要在主函数捕获exception即可,要获取异常信息,调⽤what函数,what是⼀个虚函数,派⽣类可以重写。


结束语 C++异常有关方面知识点总结完毕,对于异常容易产生的内存泄露问题,我们可以用智能指针来解决,下片博客我们来看看智能指针相关知识

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.异常的概念及使用
    • 1.1异常的概念
    • 1.2异常的抛出和捕获
    • 1.3栈展开
    • 1.4查找匹配的处理代码
    • 1.5异常重新抛出
    • 1.6异常安全问题
    • 1.7异常规范
  • 2.标准库的异常
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档