C++异常处理
(1)try语句块内抛出的异常将被catch的参数(形参)捕获,然后在catch语句块内处理此捕获的异常。
(2)当执行一个throw时,跟在throw后面的语句将不再被执行,程序的控制权由此转移到与之匹配的catch语句块。
(3)为了一次性捕获所有异常,可以使用省略号作为异常声明,即catch(...)。此语句可以与任意类型的异常匹配。
1 #include <iostream> 2 3 using namespace std; 4 5 void fun() 6 { 7 for (int i = 0; i < 10; ++i) 8 { 9 if (i == 6) 10 throw i; 11 } 12 } 13 14 int main() 15 { 16 try 17 { 18 fun(); 19 } 20 21 catch (int a) //此处的形参a捕获了抛出的i,将i作为了实参,所以此处输出i的值 22 { 23 cout << a << endl; 24 } 25 26 return 0; 27 }
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 void fun() 6 { 7 for (int i = 0; i < 10; ++i) 8 { 9 if (i == 6) 10 throw "hello"; //此处的"hello"是字面值常量,为const char*类型,而不是string类型,所以将被s2捕获 11 } //若要被string s1捕获,则需要在抛出的时候强制类型转换,即throw string("hello"). 12 } 13 14 int main() 15 { 16 try 17 { 18 fun(); 19 } 20 catch (string s1) //若要被string s1捕获,则需要在抛出的时候强制类型转换,即throw string("hello"). 21 { 22 cout << "string" << endl; 23 } 24 25 catch (const char* s2) 26 { 27 cout << "const char*" << endl; 28 } 29 30 31 32 return 0; 33 }
1 #include <iostream> 2 3 using namespace std; 4 5 void fun() 6 { 7 for (int i = 0; i < 10; ++i) 8 { 9 if (i == 6) 10 throw 'c'; 11 } 12 } 13 14 int main() 15 { 16 try 17 { 18 fun(); 19 } 20 21 22 catch (int a) 23 { 24 cout << a << endl; 25 } 26 27 catch (...) //由于没有与char类型匹配的cath语句,所以此处匹配此任意类型的catch语句 28 { 29 cout << "..." << endl; 30 }
注意: 如果catch(...)与其他几个catch语句一起出现,则catch(...)必须在最后的位置。出现在捕获所有异常语句后面的catch语句将永远不会被匹配。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南