异常的概念
异常的概念
- C语言主要通过错误发的形式处理错误,错误码本质就是对错误信息进行分类编号,拿到错误码以后还要去查询错误信息
- 异常时抛出一个对象,这个对象可以提供更全面的各种信息
异常的抛出和捕获
- 通过 throw 一个对象来引发一个异常,该对象的类型以及当前的调用链决定了应该由哪个 catch 的处理代码来处理异常
- ==当 throw 执行时,throw 后面的语句将不再被执行。==程序的执行从 throw 位置跳到与之匹配的 catch 模块:
- 沿着调用链的函数可能提早退出
- 一旦程序开始执行异常处理程序,沿着调用链创建的对象都将销毁
- 如果 throw 出现在某个 try 块内部,那么会优先找这个 try 块绑定的 catch 块尝试捕捉;但如果 throw 出现在 catch 块内部(或 try 块外),则会直接向上抛,不会找当前 try 的 catch
- 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个局部对象,所以会生成一个拷贝对象,这个拷贝的对象会在 catch 子句后销毁
栈展开
-
抛出异常后,程序暂停当前函数的执行,开始寻找与之匹配的 catch 子句
- 首先检查 throw 本身是否在 try 块内部,如果在则查找匹配的 catch 语句,如果有匹配的则跳到 catch 的地方处理
- 如果当前函数中没有 try/catch 子句,或者由 try/catch 子句但是类型不匹配,则退出当前函数,继续在外层调用函数链中查找,该过程叫做栈展开
- 如果到达 main 函数,依然没有找到匹配的 catch 子句,程序会调用标准库的 terminate 函数终止程序
- 如果找到匹配的 catch 子句处理后,catch 子句代码会继续执行

-
func1() 立刻终止,异常向上传递给调用者 func2()。
-
func2() 没有 try/catch,无法捕获异常,也立刻终止,异常继续向上传递给调用者 func3()。
-
func3() 同样没有 try/catch,继续终止并将异常传递给调用者 main()。
-
异常传递是 "向上找 catch":有catch就跳进去执行,执行完继续执行catch后面的代码,直到程序自然结束
double Divide(int a, int b)
{
try
{
// 当b == 0时抛出异常
if (b == 0)
{
string s("Divide by zero condition!");
throw s; //string
}
else
{
return ((double)a / (double)b);
}
}
catch (int errid) //只能捕获int类型异常,无法匹配string类型,异常继续传播
{
cout << errid << endl;
}
return 0;
}void Func()
{
int len, time;
cin >> len >> time;
try
{
cout << Divide(len, time) << endl;
}
catch (const char* errmsg) //只能捕获const char*类型异常,无法匹配string类型,异常继续传播到main()
{
cout << errmsg << endl;
}
cout << FUNCTION << ":" << LINE << "行执行" << endl;
}int main()
{
while (1)
{
try
{
Func();
}
catch (const string& errmsg) //在这里捕捉到
{
cout << errmsg << endl;
}
}
return 0;
}
查找匹配的处理代码
-
⼀般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配的,就选择离他位置更近的那个
-
允许从非常量向常量的类型转换,也就是权限缩小;允许数组转换成指向数组元素类型的指针,函数被转换成指向函数的指针;允许从派⽣类向基类类型的转换,这个点⾮常实用,继承体系基本就是用这个方法
-
⼀般main函数中最后都会使⽤catch(...),它可以捕获任意类型的异常,但是是不知道异常错误是什么,兜底用
#include <thread>
//⼀般大型项目程序才会使用异常,下面我们模拟设计一个服务的几个模块
//每个模块的继承都是 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;
}
异常重新抛出
-
有时catch到⼀个异常对象后,需要对错误进⾏分类,其中的某种异常错误需要进⾏特殊的处理,其他错误则重新抛出异常给外层调⽤链处理。捕获异常后需要重新抛出,直接 throw; 就可以把捕获的对象直接抛出。
void _SeedMsg(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
{
_SeedMsg(s);
break;
}
catch (const Exception& e)
{
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;
}
异常安全问题
-
异常抛出后,后⾯的代码就不再执行,前⾯申请了资源(内存、锁等),后⾯进⾏释放,但是中间可能会抛异常就会导致资源没有释放,这⾥由于异常就引发了资源泄漏,产⽣安全性的问题。
-
析构函数中抛出异常也需要捕获处理,因为资源没有全部析构会造成资源泄漏
-
需要捕获异常,释放资源后面再重新抛出
-
后⾯智能指针章节讲的RAII⽅式解决这种问题是更好的
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;
}
异常规范
- C++98中函数参数列表的后面接throw(),表示函数不抛异常,函数参数列表的后⾯接throw(类型1, 类型2...)表示可能会抛出多种类型的异常,可能会抛出的类型用逗号分割。
- C++11中函数参数列表后⾯加 noexcept 表⽰不会抛出异常,啥都不加表⽰可能会抛出异常
- ⼀个声明了 noexcept 的函数抛出了异常,程序会调用 terminate 终止程序
- noexcept(expression) 还可以作为⼀个运算符去检测⼀个表达式是否会抛出异常,可能会则返回 false,不会就返回true。
-
表达式被 noexcept 修饰,返回true
-
不是 noexcept 修饰的话看包不包含 throw 或调用可能抛出异常的函数,不包含返回true,若包含返回 false
-
他不会去执行,不会看传入的参数是什么来判断
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; //1,若是去掉noexcept就是0 cout << noexcept(Divide(1, 0)) << endl; //1,若是去掉noexcept就是0 cout << noexcept(++i) << endl; //1,内置算数运算不会抛出异常 return 0;}
-
标准库的异常
- 优先自定义异常,,而非直接用标准库异常
- C++标准库也定义了⼀套自己的⼀套异常继承体系库,基类是exception,所以我们日常写程序,需 要在主函数捕获exception即可,要获取异常信息,调用what函数,what是⼀个虚函数,派⽣类可以重写