一、C语言、C++中处理错误的方式
1、C语言处理错误
通过错误码的形式处理错误。错误码本质就是对错误信息进行分类编号,让我们拿到错误码之后还要去查询错误信息。
2、C++处理错误
异常时抛出一个对象,这个对象包含了错误的各种信息。
二、异常抛出和捕获
1、语法:(如果只看语法不理解,可以看后面的演示代码)
cpp
throw 对象//后面要跟抛出的对象
try
{
//要检查是否抛异常的代码
}
catch (抛出对象的类型) //括号里写抛出对象的类型
{
//处理异常
}
2、抛异常过程中的问题
<1>throw抛出异常对象后,会被距离它最近且类型与该对象匹配的catch捕获。
<2>throw抛出异常对象后,throw后的代码不再执行,会直接跳到捕获到这个异常的catch处。
<3>catch可能是同一个函数中的一个局部的catch,也可能是调用链中另一个函数中的catch。要注意的是,从throw跳到catch,调用链上的函数会提前结束且这些函数创建的局部变量都会被销毁。
<4>throw抛出的对象,会构造一个临时对象,就像传值返回一样。如果有移动构造也会调用移动构造的。
三、栈展开
1、过程
抛出异常后,程序暂停当前函数的执行,开始寻找与之匹配的catch子句,首先检查throw是否在try块内部,如果在,则查看有没有与之匹配的catch子句,如果有,则执行catch块。如果没有与之匹配的catch,则退出此函数,回到调用链的上一层,查看有没有匹配的catch,重复执行这个过程,直到找到与之匹配的catch或者到main函数还是没有找到与之匹配的catch。如果找到与之匹配的catch了,则执行catch块,如果到main函数还没有找到,则调用标准库的terminate函数终止程序。栈展开是在编译时发生的逻辑!!!!!也就是过这个过程是在编译时发生的,不是运行时,运行时会从throw直接跳到匹配的catch。
2、过程图

3、演示代码
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;
}
解释:抛出异常后,查看离它最近的catch (int errid),发现类型不匹配,然后退出函数Divide,看catch (const char* errmsg)是否匹配,发现也不匹配,然后退出函数Func,然后查看catch (const string& errmsg)是否匹配,发现匹配,则由catch (const string& errmsg)块处理异常。
四、查找匹配的处理代码
一般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配的那么就选择离它最近的那个。但是也有一些例外,允许从非常量向常量的类型转换,也就是权限缩小;允许数组转换成指向数组元素类型的指针,函数被转换成指向函数的指针;允许从派生类向基类类型的转换。
如果到了main函数,异常都没有被捕获,main函数中也不能捕获,那么程序就会终止。但是很多情况下是不允许程序终止的,所以一般main函数中最后都会使用catch(...)捕获异常,它可以捕获任意类型的异常,但是不知道异常错误是什么。
场景代码:
cpp
#include<iostream>
#include<string>
#include<thread>
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;
}
五、异常重新抛出
有时catch到一个异常对象后,需要对错误进行分类,其中的某种异常错误需要进行特殊的处理,其它错误则重新抛出异常给外层调用链处理。捕获异常后需要重新抛出,直接throw;就可以把捕获的对象直接抛出。
场景代码:
cpp
#include<iostream>
#include<string>
#include<thread>
using namespace std;
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 _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中是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;
}
六、异常安全问题
异常抛出后,后面的代码就不再执行,前面申请了资源(内存、锁等),后面进行释放,但是中间可能会抛异常就会导致资源没有释放,就会引起资源泄漏产生安全问题。所以中间我们需要捕获异常,然后释放资源后重新抛出。(后面的智能指针能够更好的处理这个问题)
在析构函数中,如果抛出异常也要谨慎处理。比如析构函数要释放十个资源,释放到第五个时抛出异常,则也需要捕获异常,然后释放后面没有释放的资源,最后再将异常抛出。否则也会引起资源泄露产生安全问题。
场景代码:
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;
}
七、异常规范
1、为什么要有规范
如果用户和编译器提前知道某个函数会不会抛出异常,那么就有助于简化调用函数的代码。
2、C++98中
函数参数列表后面接throw()表示函数不会抛出异常;后面接throw(类型1,类型2,...)表示可能会抛出多种类型的异常,可能抛出的类型用逗号分隔。
cpp
// 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();
3、C++11中
函数参数列表后面接noexcept表示不会抛出异常;后面什么也不接表示可能会抛异常。
cpp
// C++11
size_type size() const noexcept;
iterator begin() noexcept;
const_iterator begin() const noexcept;
如果一个函数用noexcept修饰了,但是同时又包含了throw或者调用函数可能会抛异常,编译器还是会顺利编译通过的。但是声明了noexcept的函数抛出了异常,程序会调用terminate终止程序。
noexcept(expression)可以作为一个运算符检测一个表达式是否会抛出异常,可能会则返回false,不会就返回true。
cpp
#include<iostream>
using namespace std;
//这个函数使用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;
}
八、标准库的异常
1、标准库的异常文档
2、C++标准库也定义了一套自己的异常继承体系库,基类是exception,如果我们需要捕获标准库的异常,只需要在主函数中捕获exception即可,要获取异常信息,调用what函数,what函数是一个虚函数,派生类可以重写。
