**摘要:**本文系统梳理 C++ 异常处理机制,从异常的基本概念与 C 语言错误码的对比出发,依次讲解异常的抛出与捕获、栈展开、匹配规则、异常重新抛出、异常安全问题以及异常规范,并结合标准库异常体系给出完整可运行的代码示例,帮助读者建立对 C++ 异常处理的整体认知。
1. 异常的概念
异常处理机制允许程序中独立开发的部分,在运行时对出现的问题进行通信并做出相应的处理。异常使得我们能够将问题的检测 与问题的解决过程分开:程序的一部分负责检测问题的出现,然后把解决问题的任务传递给程序的另一部分,检测环节无须知道问题处理模块的所有细节。
C 语言主要通过错误码的形式处理错误。错误码本质就是对错误信息进行分类编号,拿到错误码以后还要去查询错误信息,比较麻烦。而异常是抛出一个对象,这个对象可以携带更全面的各种信息。
2. 异常的抛出和捕获
程序出现问题时,我们通过抛出(throw)一个对象来引发一个异常,该对象的类型以及当前的调用链决定了应该由哪个 catch 的处理代码来处理该异常。
- 被选中的处理代码是调用链中与该对象类型匹配、且离抛出异常位置最近的那一个。
- 根据抛出对象的类型和内容,程序的抛出异常部分告知异常处理部分到底发生了什么错误。
- 当
throw执行时,throw后面的语句将不再被执行,程序的执行从throw位置跳到与之匹配的catch模块。 catch可能是同一函数中的一个局部catch,也可能是调用链中另一个函数中的catch,控制权从throw位置转移到了catch位置。
这里还有两个重要的含义:
- 沿着调用链的函数可能提早退出。
- 一旦程序开始执行异常处理程序,沿着调用链创建的对象都将销毁。
抛出异常对象后,会生成一个异常对象的拷贝。因为抛出的异常对象可能是一个局部对象,所以会生成一个拷贝对象,这个拷贝的对象会在 catch 子句后销毁(这里的处理类似于函数的传值返回)。
3. 栈展开
抛出异常后,程序暂停当前函数的执行,开始寻找与之匹配的 catch 子句:
- 首先检查
throw本身是否在try块内部,如果在则查找匹配的catch语句,如果有匹配的,则跳到catch的地方进行处理。 - 如果当前函数中没有
try/catch子句,或者有try/catch子句但是类型不匹配,则退出当前函数,继续在外层调用函数链中查找。上述查找catch的过程被称为栈展开。 - 如果到达
main函数,依旧没有找到匹配的catch子句,程序会调用标准库的terminate函数终止程序。 - 如果找到匹配的
catch子句,处理后catch子句代码会继续执行。
下面通过一个除零异常的例子,观察异常在不同调用层级之间如何传递:
cpp
#include <iostream>
#include <string>
using namespace std;
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;
}
在 Divide 中抛出的是 string 类型对象,本层的 catch(int) 与 Func 中的 catch(const char*) 都无法匹配,最终由 main 中的 catch(const string&) 捕获,这正是栈展开的典型过程。
4. 查找匹配的处理代码
一般情况下,抛出对象和 catch 是类型完全匹配的;如果有多个类型匹配的,就选择离它位置更近的那个。但也有一些例外,允许以下转换:
- 从非常量向常量的类型转换,也就是权限缩小。
- 数组转换成指向数组元素类型的指针,函数被转换成指向函数的指针。
- 从派生类向基类类型的转换,这个点非常实用,实际中继承体系基本都是用这种方式设计的。
如果到 main 函数,异常仍旧没有被匹配就会终止程序。不是发生严重错误的情况下,我们是不期望程序终止的,所以一般 main 函数中最后都会使用 catch(...),它可以捕获任意类型的异常,但是不知道异常错误是什么。
下面模拟一个服务的几个模块,每个模块的异常类都继承自 Exception,最后统一捕获基类:
cpp
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cstdlib>
using namespace std;
// 一般大型项目程序才会使用异常,下面我们模拟设计一个服务的几个模块
// 每个模块的继承都是 Exception 的派生类,每个模块可以添加自己的数据
// 最后捕获时,我们捕获基类就可以
class Exception
{
public:
Exception(const string& errmsg, int id)
: _errmsg(errmsg)
, _id(id)
{}
virtual string what() const
{
return _errmsg;
}
int getid() 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& type)
: Exception(errmsg, id)
, _type(type)
{}
virtual string what() const
{
string str = "HttpException:";
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};
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();
}
int main()
{
srand(time(0));
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;
}
5. 异常重新抛出
有时 catch 到一个异常对象后,需要对错误进行分类:其中的某种异常错误需要进行特殊的处理,其他错误则重新抛出异常给外层调用链处理。捕获异常后需要重新抛出,直接 throw; 就可以把捕获的对象直接抛出。
下面的程序模拟了聊天时发送消息的场景:发送失败会捕获异常,但可能在电梯、地下室等场景手机信号不好,则需要多次尝试;如果多次尝试都发送不出去,就需要捕获异常再重新抛出。其次如果不是网络差导致的错误,捕获后也要重新抛出。
cpp
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void _SendMsg(const string& s)
{
if (rand() % 2 == 0)
{
throw HttpException("网络不稳定,发送失败", 102, "put");
}
else if (rand() % 7 == 0)
{
throw HttpException("你已经不是对象的好友,发送失败", 103, "put");
}
else
{
cout << "发送成功" << endl;
}
}
void SendMsg(const string& s)
{
// 发送消息失败,则再重试 3 次
for (size_t i = 0; i < 4; i++)
{
try
{
_SendMsg(s);
break;
}
catch (const Exception& e)
{
// 捕获异常,if 中是 102 号错误,网络不稳定,则重新发送
// 捕获异常,else 中不是 102 号错误,则将异常重新抛出
if (e.getid() == 102)
{
// 重试三次以后还失败了,则说明网络太差了,重新抛出异常
if (i == 3)
throw;
cout << "开始第" << i + 1 << "次重试" << endl;
}
else
{
throw;
}
}
}
}
int main()
{
srand(time(0));
string str;
while (cin >> str)
{
try
{
SendMsg(str);
}
catch (const Exception& e)
{
cout << e.what() << endl << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
6. 异常安全问题
异常抛出后,后面的代码就不再执行。如果前面申请了资源(内存、锁等),后面进行释放,但中间可能会抛异常,就会导致资源没有释放,这里由于异常就引发了资源泄漏,产生安全性的问题。中间我们需要捕获异常,释放资源后再重新抛出;当然,后面智能指针章节讲的 RAII 方式解决这种问题是更好的。
其次,析构函数中如果抛出异常也要谨慎处理。比如析构函数要释放 10 个资源,释放到第 5 个时抛出异常,则也需要捕获处理,否则后面的 5 个资源就没释放,也资源泄漏了。《Effective C++》第 8 个条款也专门讲了这个问题:别让异常逃离析构函数。
cpp
#include <iostream>
using namespace std;
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;
}
7. 异常规范
对于用户和编译器而言,预先知道某个程序会不会抛出异常大有裨益,知道某个函数是否会抛出异常有助于简化调用函数的代码。
- C++98 中函数参数列表的后面接
throw(),表示函数不抛异常;函数参数列表的后面接throw(类型1, 类型2...)表示可能会抛出多种类型的异常,可能抛出的类型用逗号分割。 - C++98 的这种方式过于复杂,实践中并不好用。C++11 中进行了简化:函数参数列表后面加
noexcept表示不会抛出异常,什么都不加表示可能会抛出异常。 - 编译器并不会在编译时检查
noexcept。也就是说,如果一个函数用noexcept修饰了,但是同时又包含了throw语句或者调用的函数可能会抛出异常,编译器还是会顺利编译通过(有些编译器可能会报个警告)。但是一个声明了noexcept的函数抛出了异常,程序会调用terminate终止程序。 noexcept(expression)还可以作为一个运算符去检测一个表达式是否会抛出异常,可能会则返回false,不会就返回true。
cpp
#include <iostream>
#include <new>
using namespace std;
// 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;
}
需要注意的是,noexcept 运算符判断的是表达式本身是否声明可能抛出异常 ,而不是运行时是否真的抛出异常,因此 noexcept(Divide(1, 0)) 的结果同样为 true。
8. 标准库的异常
C++ 标准库也定义了一套自己的异常继承体系,基类是 exception。所以日常写程序,需要在主函数捕获 exception 即可;要获取异常信息,调用 what 函数,what 是一个虚函数,派生类可以重写。
标准库异常体系可参考官方文档:exception - C++ Reference
| 异常类 | 说明 |
|---|---|
std::exception |
所有标准异常的基类,提供虚函数 what() |
std::bad_alloc |
new 申请内存失败时抛出 |
std::bad_cast |
动态类型转换 dynamic_cast 失败时抛出 |
std::out_of_range |
访问越界,如 vector::at 下标非法 |
std::logic_error |
逻辑错误类异常的基类 |
std::runtime_error |
运行时错误类异常的基类 |
9. 小结
- 异常把错误检测 与错误处理解耦,比错误码能携带更丰富的信息。
throw后沿调用链进行栈展开,匹配最近的、类型兼容的catch;到main仍未匹配则调用terminate。- 利用继承体系设计异常类,在
main中捕获基类引用,是大型项目的常见做法。 throw;可重新抛出当前异常,用于分层处理与重试逻辑。- 注意异常安全:资源释放要放在捕获路径中,或使用 RAII;不要让异常逃离析构函数。
- C++11 起用
noexcept声明不抛异常,并可用noexcept(expr)运算符检测表达式。