C++异常处理入门:try与catch机制详解
C++引入了Exception机制来解决运行时错误。本文解析如何区分错误类型,并通过try-catch结构捕获异常,包括直接抛出、函数调用中抛出及多层嵌套时的执行流跳转原理。
程序错误的分类
开发过程中常见的错误主要分为三类:
- 语法错误:编译链接阶段即可发现,不符合语法规则的代码无法生成可执行程序。
- 逻辑错误:代码思路有误导致目标未达成,通常通过调试解决。
- 运行时错误:程序运行期间发生的错误,如除数为0、内存分配失败、数组越界等。这是C++异常机制主要解决的问题。
若放任运行时错误不管,系统会终止程序,即发生Crash。异常机制允许我们捕获这些错误,进行恢复处理或在终止前通知用户。
捕获异常基础
捕获异常的语法由关键字 try 和 catch 组成:
try{
// 可能抛出异常的语句
}catch(exceptionType variable){
// 处理异常的语句
}
try块用于“检测”可能引发异常的代码,catch块用于“抓住”并处理被检测到的异常。若try内无异常抛出,则catch不执行。
第1步:理解[]与at()的差异
通过字符串访问对比,明确何时会触发异常。以下为演示代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "http://c.biancheng.net";
char ch1 = str[100]; //下标越界,ch1为垃圾值
cout<<ch1<<endl;
char ch2 = str.at(100); //下标越界,抛出异常
cout<<ch2<<endl;
return 0;
}
运行上述代码,在输出ch1后程序崩溃。原因如下:
[ ]运算符不进行越界检查,仅返回未知内存值;而at()是string类的成员函数,检测到越界时会主动抛出异常。由于该异常未被处理,系统执行默认操作(终止程序)。
第2步:使用try-catch避免崩溃
引入异常捕获机制,分别测试[ ]越界与at()越界的处理效果:
#include <iostream>
#include <string>
#include <exception>
using namespace std;
int main(){
string str = "http://c.biancheng.net";
try{
char ch1 = str[100];
cout<<ch1<<endl;
}catch(exception e){
cout<<"[1]out of bound!"<<endl;
}
try{
char ch2 = str.at(100);
cout<<ch2<<endl;
}catch(exception &e){ //exception类位于<exception>头文件中
cout<<"[2]out of bound!"<<endl;
}
return 0;
}
运行结果为:[2]out of bound!。
说明:
1. 第一个try未捕获到异常,输出了无意义的字符。因为[ ]不会显式抛出异常,所以try检测不到任何错误。
2. 第二个try检测到at()抛出的异常,交由catch处理。
3. throw必须在代码中明确抛出,try才能感知。例如将索引改为极大值可能导致底层内存访问错误,这种隐式崩溃同样不在try-catch的常规捕获范围内。
核心流程为:抛出(Throw) → 检测(Try) → 捕获(Catch)。
发生异常的位置与执行流跳转
异常不仅发生在当前try块中,也可发生在其调用的函数或函数的深层调用链中。一旦发生异常,程序的执行流会发生跳转:
- 当前块抛出:
try内的throw直接触发捕获,后续cout语句跳过。
#include <iostream>
#include <exception>
using namespace std;
int main(){
try{
throw "Unknown Exception";
cout<<"This statement will not be executed."<<endl;
}catch(const char* &e){
cout<<e<<endl;
}
return 0;
}
- 子函数抛出:
try内调用的函数func()抛出异常,会被外层try捕获。func()内及try内抛出点后的代码均不被执行。
#include <iostream>
#include <exception>
using namespace std;
void func(){
throw "Unknown Exception";
cout<<"[1]...not executed."<<endl;
}
int main(){
try{
func();
cout<<"[2]...not executed."<<endl;
}catch(const char* &e){
cout<<e<<endl;
}
return 0;
}
- 调用链回退:若
func_outer()调用func_inner(),而func_inner()抛出异常,执行流将沿调用链向上回退,直到遇见try为止。中间过程所有未执行的代码(含所有层级函数内抛出点之后的语句)全部跳过。
#include <iostream>
#include <exception>
using namespace std;
void func_inner(){
throw "Unknown Exception";
}
void func_outer(){
func_inner();
}
int main(){
try{
func_outer();
cout<<"[3]...not executed."<<endl;
}catch(const char* &e){
cout<<e<<endl;
}
return 0;
}
处理完catch块后,程序继续执行后续代码,恢复正常流。以上就是C++异常处理中try和catch机制的详细内容,更多关于C++异常处理的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













