异常处理机制允许程序中独立开发的部分能够在运行时对出现的问题进行通信并做出相应的处理,异常使得我们能够将问题的检测与解决问题的过程分开,程序的一部分负责检测问题的出现,然后解决问题的任务传递给程序的另一部分,检测环节无须知道问题的处理模块的所有细节。
在C语言中,我们主要通过错误码的形式处理问题,错误码本质就是对错误信息进行分类编号,拿到错误码以后还要去查询错误信息,比较麻烦。
如果我们是在main函数中记录日志,处理错误,那就有可能会更麻烦,如果错误是在某个函数中出现的,那么这个错误会一层一层的往main函数中传递,然后在main函数中记录日志和处理错误

但是在C++中,我们不是这么做的,异常时抛出一个对象,这个对象可以包含更全面的各种信息,比如我们在上图中的f4函数中出现了异常,则在f4函数中通过throw,抛出一个异常对象,然后在main函数中,对异常进行捕获——

#include<iostream>
using namespace std;
double Divide(int a, int b)
{
//当b==0时抛出异常
if (b == 0)
{
string s("Divide by zero andition!");
throw s;
}
else
{
return (double)a / (b);
}
}
void Func()
{
int len, time;
cin >> len >> time;
Divide(len, time);
}
int main()
{
Func();
return 0;
}ok,在上面的代码中,当抛出异常后,并没有被捕获,会导致程序直接被终止!!!

发生异常必须被捕获,如果不捕获异常就会直接终止程序(这是一件很危险的事情)
我们使用try() catch() 进行捕获异常——

抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的对象可能是一个局部对象,所以生成一个拷贝对象,捕获的就是这个拷贝对象,这个拷贝的对象会在catch子句后销毁(类似于函数的传值返回)
当我们再一次抛出异常后,异常就别被捕获了这样就不会导致程序的直接终止——

并且当我们对上面的抛出异常和捕获异常的代码时,我们会发现——
catch的逻辑一定是由throw(出现异常)决定的,出现异常直接跳到catch的地方去,在catch的地方被捕获
被选中的处理代码时调用链中的与该对象类型匹配且抛出异常位置最近的那一个(可能会有多个catch匹配,找位置更近的一个)。根据抛出对象的类型和内容,程序的抛出异常部分告知异常处理部分到底发生了什么错误
当throw执行时(抛出一个异常),throw后面的语句不再被执行。程序的执行从throw位置跳到与之匹配的catch模块,这个与之匹配的catch可能是同一函数中的一个局部的catch,也可能是调用链中另一个函数的catch ,程序的控制权从throw位置转移到catch位置。
这里有两个重要的含义:
ok,除了上面的那种捕获代码,库中还有一种——
#include<iostream>
using namespace std;
double Divide(int a, int b)
{
//当b==0时抛出异常
if (b == 0)
{
throw exception("Divide by zero andition!");
}
else
{
return (double)a / (b);
}
}
void Func()
{
int len, time;
cin >> len >> time;
Divide(len, time);
}
int main()
{
try
{
Func();
}
catch (const exception& e)
{
cout << e.what() << endl;
//e.what()就是说你的异常是什么
}
return 0;
}这里有个需要注意的地方:throw后(抛出一个异常后),并不是直接跳到与之匹配的catch语句上,这里需要经过一个过程——
throw后(抛出一个异常后),并不是直接跳到与之匹配的catch语句上,而是在编译时进行查找匹配的catch
就是说,如果在当前函数栈中没有找到相应的catch子句,那么就要到这个调用链中去找,但是出了当前函数的作用域后,该函数栈帧该析构析构,里面有资源的该释放的释放,该销毁的销毁
我们通过代码来看一下——
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;
}
通过上面的代码,我们就可以很清晰的看出,如果找到匹配的catch子句并处理完异常后,catch子句后面的代码会继续执行
一般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配,就选择离抛出异常的位置更近的那个
凡事都有个但是,但是也有一些例外:
如果到main函数,异常依旧没有被捕获,那么程序就会被终止(这是很危险的),不是发生严重错误的情况下,我们是不期望程序终止的,所以一般main函数中最后都会使用catch(...) ,它可以捕获任意类型的异常,但是不知道异常是什么。
#include<iostream>
using namespace std;
double Divide(int a, int b)
{
//当b==0时抛出异常
if (b == 0)
{
/*string s("Divide by zero andition!");
throw s;*/
throw exception("Divide by zero andition!");
}
else
{
return (double)a / (b);
}
}
void Func()
{
int len, time;
cin >> len >> time;
Divide(len, time);
}
int main()
{
try
{
Func();
}
catch (...)
{
cout << "未知类型错误" << endl;
}
return 0;
}
#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;就可以把捕获的对象直接拋出。
就比如:有时候,我们在微信上聊天,突然信号不好,如果一次发送不出去,就提示不能发送的话,这种体验感是很差的,所以需要尝试多次,如果多次尝试都发不出去,则需要捕获异常在重新抛出;还有一种就是不是由信号差引起的,捕获后也要重新抛出
ok,我们通过模拟代码来看一下:
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;
}
}
// 网络不稳定,要求重试3次,均失败
void SendMsg(const string& s)
{
for (size_t i = 0; i < 4; i++)
{
try
{
_SendMsg(s);
// 走到这里代表成功了,跳出循环
break;
}
catch (const Exception& e)
{
if (e.getid() == 102)
{
if (i == 3)
throw;
cout << "开始第" << i + 1 << "重试" << endl;
}
else
{
// 重新抛出异常
//throw e;
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;
}运行结果——

通过前面的学习,我们知道当一个异常被throw后,throw后面的代码就不再执行,那如果在throw的后面,我没有将申请的资源的进行释放的话,这就造成了资源的泄露!!!
这种情况下,我们需要捕获异常,释放资源后再重新抛出,后面智能指针章节讲的RALL方式解决这种问题是更好的
在《Effective C++》中也讲到,别人异常逃离析构函数!!!
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];
int len, time;
cin >> len >> time;
try {
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 (...)
{
cout << "Unkown Exception" << endl;
}
return 0;
}对于一个程序员和编译器而言,如果能预先知道某个程序会不会抛出异常会很有用处,知道某个函数是否会抛出异常有助于简化调用函数的代码。
可能会抛出的类型用逗号分割。在C++98的方法中,有一个问题,就是我有可能不知道会抛那种类型的异常;还有一个问题是:这个不是强制的,有人按规范来,有人不按规范来
所以,在C++11中进行了简化——
就比如库中的push_back——

这就说明push_back可能会抛异常

size就不会抛异常

noexcept(expression) 还可以作为一个运算符去检测一个表达式是否会抛出异常。
double Divide(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
int main()
{
int i = 2;
cout << noexcept(Divide(1, 0)) << endl;
cout << noexcept(Divide(1, 1)) << endl;
cout << noexcept(Divide(0,3)) << endl;
cout << noexcept(++i) << endl;
return 0;
}
C++标准库也定义了自己的一套异常继承体系库,基类是exception,所以我们日常写程序,需要在主函数捕获exception即可,要获取异常信息,调用what函数,what是一个虚函数,派生类可以重写。

uu们,本文的内容到这里就全部结束了啦!
结语:希望对学习C++相关内容的uu们能够有所帮助,不要忘记给博主“一键三连”哦!