作为一名合格的程序员,我们在开发过程中必须了解程序的异常问题,只有这样我们才能在工程实践中更加游刃有余,在项目开发中更加得心应手!!!那么我们废话不多说,直接进入我们的正式环节。
一. 异常的概念
1. 异常处理机制允许我们程序中的独立开发的模块能够在运行时就把程序出现的问题进行及时通信并做出相应的解决处理,异常使得我们能够将问题的检测与解决问题的过程分开,程序的⼀部分模块负责检测问题,然后解决问题的任务则传递给程序的另⼀模块,检测环节无须知道问题的处理模块的所有相关问题细节。
2. 之前我们在C语言中主要通过错误码的形式来处理异常,错误码本质就是对错误信息进行分类编号,但是我们拿到错误码以后还要去查询对应的错误信息,这样相对就比较麻烦。而在发生异常时抛出⼀个对象,这个对象可以包含函数更全面的各种异常信息,这样就方便多了。
二. 异常的抛出与捕获
1. 当程序出现问题时,我们通过抛出(throw)⼀个对象来引发⼀个异常,该对象的类型以及当前的调用
链决定了应该由哪个try-catch的处理代码来处理该异常。
2. 被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那⼀个try-catch组合。根据抛出对象的类型和内容,程序的抛出异常部分告知异常处理部分到底发生了什么错误。
3. 当throw在执行时,throw后面的语句将不再被执行。程序的执行会从throw位置直接跳到与之匹配的catch代码模块,catch可能是同⼀函数中的⼀个局部的catch,也可能是调用链中另⼀个函数中的catch,那么代码控制权就从throw位置转移到了catch位置。这里还有两个我们在抛异常时需要注意的小问题:
① 沿着调用链的函数可能提早退出,并未执行。
② ⼀旦程序开始执行异常处理程序,沿着调用链创建的对象都将调用对应的析构函数来销毁。
4. 抛出异常对象后,调用链在接收时会接收这个异常对象的拷贝,因为抛出的异常对象可能是⼀个局部对象,所以会生成⼀个拷贝对象,这个拷贝的对象会在catch子句执行后销毁。
三. 栈展开
1. 当我们抛出异常后,程序会暂停当前函数的执行,开始寻找与之匹配的catch子句,程序会首先检查throw本身是否在try块内部,如果在则查找该try-catch组合中的catch语句;如果有匹配的类型,则跳到catch的地方进行处理。
2 . 如果当前函数中没有try-catch子句,或者有try/catch子句但是类型不匹配,则退出当前函数,继续
在外层的调用函数链中查找,上述查找catch过的程被称为栈展开。
3. 如果查找catch子句找到了main函数,但是依旧没有找到匹配的catch子句时,那么程序就会调用C/C++标准库的 terminate 函数终止该程序。
4. 如果找到匹配的catch子句处理后,那么该catch子句后的代码会继续执行。
栈展开示例:

代码示例:
cpp
double Divide(int len,int time)
{
//try和catch必须成对出现
try
{
if (time == 0)
{
string s("Divide by zero!");
throw s;
}
else
{
return (double)len / time;
}
}
catch (const int& e)
//catch (const string& e)
{
cout << e << endl;
}
return 0;
}
void Func()
{
try
{
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
}
//catch (const int& e)
catch (const string& e)
{
cout << e << endl;
}
cout << __FUNCTION__ << "执行" << __LINE__ << endl;
}
int main()
{
try
{
Func();
}
//catch (const int& e)
catch (const string& e)
{
cout << e << endl;
}
catch (...) //捕获任意类型的异常
{
cout << "未知错误" << endl;
}
return 0;
}
四. 查找匹配的处理代码
1. ⼀般情况下抛出异常的对象的类型和catch子句的类型是完全匹配的。如果有多个类型匹配的catch子句,那么异常对象跳转时就选择离它位置最近的那个catch子句。
2. 但是注意也有⼀些例外:
① 允许从非常量向常量的类型转换,也就是权限的缩小。
② 允许数组转换成指向数组元素类型的指针(即数组指针),函数被转换成指向函数的指针(即函数指针)。
③ 允许从派⽣类向基类类型的转换,这个例外非常实用,在实际继承体系中基本都是用这个方式设计的,某种程度上也体现了多态的思想。
3. 如果一直匹配到main函数,异常仍旧没有被匹配那么编译器就会终止程序。在不是发生严重错误的情况下,我们是不期望程序直接终止的,所以⼀般main函数中最后都会使用catch(...)来捕获可能发生的任意类型的异常,只是不知道异常错误具体是什么。
代码示例:
cpp
class Exception
{
public:
Exception(const string& errmsg,int id)
:_errmsg(errmsg)
,_id(id)
{ }
virtual string what() const
{
return _errmsg;
}
int get_pid() const
{
return _id;
}
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 HttpException :public Exception
{
public:
HttpException(const string& errmsg,int id,const string& httptype)
:Exception(errmsg,id)
,_httptype(httptype)
{ }
virtual string what() const
{
string str = "HttpException";
str += _errmsg;
str += ":";
str += _httptype;
return str;
}
private:
string _httptype;
};
void SQLMgr()
{
if (rand() % 7 == 0)
{
throw SqlException("权限不足", 100, "select * from name = '张三'");
}
else
{
cout << "SQLMgr 调用成功" << endl;
}
}
void CacheMgr()
{
if (rand() % 5 == 0)
{
throw CacheException("权限不足", 100);
}
else if (rand() % 6 == 0)
{
throw CacheException("数据不存在", 101);
}
else
{
cout << "CacheMgr 调用成功" << endl;
}
SQLMgr();
}
void HttpServer()
{
if (rand() % 3 == 0)
{
throw HttpException("请求资源不存在", 100, "get");
}
else if (rand() % 4 == 0)
{
throw HttpException("权限不足", 101, "post");
}
else
{
cout << "HttpServer调用成功" << endl;
}
CacheMgr();
}
#include <Windows.h>
#include <thread>
int main()
{
srand(time(0));
while (1)
{
//Sleep(1000);
this_thread::sleep_for(chrono::seconds(1));
try
{
HttpServer();
}
catch (const Exception& e)
{
cout << e.what() << endl;
}
catch(...)
{
cout << "未知异常" << endl;
}
}
return 0;
}
五. 异常重新抛出
在实际开发中我们有时catch到⼀个异常对象后,还需要对异常类型进行分类,对于其中的某种异常错误需要进行特殊的处理,其他类型的错误则重新抛出异常给外层调用链来处理。捕获异常后需要重新抛出,直接 throw,就可以把捕获的对象直接抛出。
代码示例:
cpp
class Exception
{
public:
Exception(const string& errmsg,int id)
:_errmsg(errmsg)
,_id(id)
{ }
virtual string what() const
{
return _errmsg;
}
int get_pid() const
{
return _id;
}
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 HttpException :public Exception
{
public:
HttpException(const string& errmsg,int id,const string& httptype)
:Exception(errmsg,id)
,_httptype(httptype)
{ }
virtual string what() const
{
string str = "HttpException";
str += _errmsg;
str += ":";
str += _httptype;
return str;
}
private:
string _httptype;
};
void _SeedMsg(const string& s)
{
if (rand() % 2 == 0)
{
throw HttpException("网络不稳定,请重新发送",102,"put");
}
else if(rand()%7==0)
{
HttpException("你不是对方的好友,发送失败", 103, "put");
}
else
{
cout << "发送成功" << endl;
}
}
void SeedMsg(const string& s)
{
for (size_t i = 0; i < 4; i++)
{
try
{
_SeedMsg(s);
break;
}
catch(const Exception& e)
{
if (e.get_pid() == 102)
{
if (i == 3)
{
throw; //可直接throw
//throw e;
}
cout << "开始第" << i+1 << "次重试" << endl;
}
else
{
throw;
}
}
}
}
#include <Windows.h>
int main()
{
srand(time(0));
try
{
string str;
while (cin >> str)
{
//Sleep(1000);
SeedMsg(str);
}
}
catch (const Exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "未知错误" << endl;
}
return 0;
}
六. 异常安全问题和规范
1. 我们在一些场景中可能会出现这种情况:在异常抛出后,导致后面的代码不再执行,并且在抛异常之前我们还动态申请了资源,在后面进行释放,但是中间可能会抛异常就会导致资源没有释放。这⾥由于异常就引发了资源内存泄漏,产生安全性的问题。所以中间我们需要在捕获异常的过程中释放资源,释放资源之后再重新抛出。
2. 另外,在析构函数中,如果抛出异常也要谨慎处理,比如在析构函数中原本要释放十个我们动态申请的资源,但是代码在执行时,释放到第五个资源时就抛出了异常,那么这里也需要捕获处理,否则后面的五个资源就没有释放,就导致资源泄漏了。
3. 对于用户和编译器而言,预先知道某个程序会不会抛出异常大有裨益,知道某个函数是否会抛出异常有助于简化调用函数的代码,同时防止程序异常导致出乎意料的崩溃。
4. C++98中函数参数列表的就后面加上throw(),表示函数不会抛异常,函数参数列表的后面接throw(类型1,类型2...)表示可能会抛出多种类型的异常,可能会抛出的类型用逗号分割。
5. C++98的方式这种方式过于复杂,实践中并不好用,C++11中进行了简化,函数参数列表后⾯加noexcept表示不会抛出异常,啥都不加表示可能会抛出异常。
6 . 编译器并不会在编译时检查noexcept,也就是说如果⼀个函数⽤noexcept修饰了,但是同时又包含了throw语句或者调用的函数可能会抛出异常,编译器还是会顺利编译通过的(有些编译器可能会
报个警告)。但是如果⼀个声明了noexcept的函数抛出了异常,那么程序就会调用 terminate函数 来终止程序。
7. noexcept(expression)还可以作为⼀个运算符去检测⼀个表达式是否会抛出异常,可能会抛出则返回false,不会就返回true。
代码示例:
cpp
double Divide(int len, int time)
{
try
{
if (time == 0)
{
string s("Divide by zero!");
throw s;
}
else
{
return (double)len / time;
}
}
catch (const string& e)
{
cout << e << endl;
}
return 0;
}
void Func()
{
int* p = new int(1);
try
{
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
delete p;
p = nullptr;
}
catch (...)
{
delete p;
p = nullptr;
throw;
}
delete p;
p = nullptr;
}
int main()
{
try
{
Func();
}
catch (const string& e)
{
cout << e << endl;
}
catch (const Exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "未知错误" << endl;
}
string str;
int i = 0;
cout << noexcept(Divide(1, 2)) << endl; //检查是否可能会抛异常
cout << noexcept(Divide(1, 2)) << endl;
cout << noexcept(str += "xx") << endl;
cout << noexcept(str.size()) << endl;
cout << noexcept(++i) << endl;
return 0;
}