🚀异常概念
异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。
如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。
#include <iostream>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
throw "Division by zero condition!";
else
return ((double)a / (double)b);
}
void Func()
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg) {
cout << errmsg << endl;
}
return 0;
}如果没有出现异常,正常执行,不走catch,执行结束:

如果在检测块出现了异常,则直接由异常处返回到catch处,并输出报错信息。

catch会对throw出的异常进行匹配,如果throw没有对应类型的异常,那么将会报错:
#include <iostream>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
throw "Division by zero condition!";
else
return ((double)a / (double)b);
}
void test()
{
int i;
cin >> i;
if (i % 2 == 0)
throw i;
}
void Func()
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
test();
}
int main()
{
try
{
Func();
}
catch (const char* errmsg) {
cout << errmsg << endl;
}
return 0;
}
throw的类型没有对应的catch相匹配,那么就会报错。这里的调用链逻辑就是:main -> func -> devision -> test -> catch。如果采用传统C语言错误码返回的方式这里需要返回的层数就会过多。
异常的抛出和匹配原则:
在函数调用链中异常栈展开匹配原则:

当然,C++这种异常的处理方式大概率会打乱我们原本的执行流,所以一般在项目当中不会让异常跳出既定执行流,通常是将异常放入日志,以后通过日志分析异常出现原因。
而catch(…)保证了程序的健壮性,如果一个大型项目里面,有一个程序出现了异常并且抛出了异常,但是没有匹配的类型,所以这个程序就会挂,为了不让程序挂,通常我们写程序的时候会加上catch(…),可以用来接收所有的异常,如果有特殊的异常没有匹配的类型,就会被catch(…)捕获,就不至于挂了,因为不知道具体是哪种异常,所以catch(…)内无法判断异常类型,保证程序的健壮性是其意义 所在。
异常规范:
// 这里表示这个函数会抛出A/B/C/D中的某种类型的异常
void fun() throw(A,B,C,D);
// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);
// 这里表示这个函数不会抛出异常
void* operator new (std::size_t size, void* ptr) throw();这里可以在函数后声明此函数存在哪些异常,但是这个规范的漏洞很多,例如以下代码实际上是存在异常的:
#include <iostream>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
void func() throw()
{
int len, int time;
cin >> len >> time;
cout << Division(len, time);
}
int main()
{
try
{
func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
return 0;
}
这个时候给人的误导性很强,而且这个语法因为要兼容C语言所以并不是强制实现的,所以可能有些人按照规范走,有些人不按照规范走。而C++11有一个新语法:
// C++11中新增的 noexcept 表示不会抛异常
thread() noexcept;
thread(thread && x) noexcept; 所以,不需要在函数前面声明了,如果函数体内有异常的话,不要在函数声明后面加上任何东西,如果确定没有异常抛出的话,就加上 noexcept,不过这些语法也防不住有心的人。这个地方的设计个人觉得不是很好。
工程实例中常用的异常体系如下:

class Exception
{
public:
Exception(const string& errmsg, int id) :
_errmsg(errmsg)
, _id(id)
{}
virtual string what() const// 子类对虚函数重写
{
return _errmsg;
}
protected:
string _errmsg; // 错误描述
int _id; // 错误编号
};而子类继承父类,每一个服务模块都需要继承Exception基类,并且在子类中重写what()函数,这样我们在main函数中就不需要设置多个catch来捕获不同类型的异常了。
只需要在main函数中创建父类对象的引用,当子类中有错误抛出的时候,会返回到main函数的父类,父类指向子类,就完成了一次多态调用,调用子类重写的what()函数。下面是一个简单的示例调用:
#include <iostream>
#include <string>
#include <windows.h>
#include <cstdlib>
#include <ctime>
using namespace std;
class Exception
{
public:
Exception(const string& errmsg, int id) :
_errmsg(errmsg)
, _id(id)
{}
virtual string what() const// 子类对虚函数重写
{
return _errmsg;
}
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 = "SqlExcption:";
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 waht() const
{
string str = "CacheException";
str += _errmsg;
return str;
}
};
class HttpServerException : public Exception
{
public:
HttpServerException(const string& errmsg, int id, const string& type)
:Exception(errmsg, id), _type(type)
{}
virtual string what() const
{
string str = "HttpServerException";
str += _type;
str += ";";
str += _errmsg;
return str;
}
private:
const string _type;
};
void SqlMgr()
{
srand(time(0));
if (rand() % 7 == 0)
{
throw SqlException("权限不足", 100, "Select * from name = '张三'");
}
cout << "_________________________执行结束_________________________" << endl;
}
void CacheMgr()
{
srand(time(0));
if (rand() % 5 == 0)
{
throw CacheException("权限不足", 100);
}
else if (rand() % 6 == 0)
{
throw CacheException("数据不存在", 101);
}
SqlMgr();
}
void HttpServer()
{
srand(time(0));
if (rand() % 3 == 0)
{
throw HttpServerException("权限不足", 100, "get");
}
else if (rand() % 4 == 0)
{
throw HttpServerException("数据不存在", 101, "post");
}
CacheMgr();
}
int main()
{
while (1)
{
Sleep(1000);
try {
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 这里走了一个多态, 父类指针指向子类的对象,指向谁调用谁
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
构造函数与析构函数内抛异常是一件很严重的事情,如果构造函数有两个指针需要初始化,当第一个指针进行初始化的时候却抛异常了,这个时候就会跳出构造,导致对象创建不完整,除了作用域会调用析构函数,而类构造函数中有一个指针没有初始化,也就是说有一个空指针,这个时候调用析构函数就会导致delete空指针,导致内存泄漏。
还有一种情况,当new/malloc对象之后,在free/delete之前发生了异常,并且是未知异常,这样就会被catch(…)捕获,但是由于是未知异常,不会释放资源,导致内存泄漏问题。如果编写线程demo在临界区内抛异常可能会导致死锁问题,当临界区异常为未知异常时,被catch(…)捕获,也没办法解锁。
所以大部分的时候我们不要在程序中间捕获异常,解决方法可以使用 异常的重新抛出:
#include <iostrem>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
void Func()
{
int* array = new int[10];
try {
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (...)// 如果没有二次抛出异常这里的delete就不会被执行,导致内存泄漏
{
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 << "this is a unknown abnormal" << endl;
}
return 0;
}如果func内部抛异常了,这个时候就会跳出delete的代码,导致资源没释放,所以我们可以选择二次抛出异常,在catch内先清理资源,再把异常抛出到下一级。在二次抛出的try代码块里的函数可能会有多层,可能会是不同的异常,这样异常出来之后就不能匹配了,或者被main函数内的catch(…)捕获,又会导致没法delete,实属治标不治本,但是我们二次抛出异常可以使用catch(…)抛出,不论try内检测了什么异常,都会被catch(…) 返回,也能保证一定会捕获异常,也就能清理资源了。
try {
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (...)// 如果没有二次抛出异常这里的delete就不会被执行,导致内存泄漏
{
cout << "delete []" << array << endl;
delete[] array;
throw;
}不也有一些极端的场景,处理起来让人很头疼:
void func()
{
int* p1 = new int[10];
int* p2, * p3;
try {
p2 = new int[30];
try {
p3 = new int[20];
}
catch (...)
{
delete[] p3;
delete[] p2;
throw;
}
}
catch(...)
{
delete[] p1;
throw;
}
delete[] p1;
delete[] p2;
delete[] p3;
}
int main()
{
try
{
func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
return 0;
}比如这里new了三个数组,如果要对这三个抛异常,那么我们只能像上述方式捕获异常,这样代码的观感不好,并且写起来也不好。我们后面学了智能指针之后,这个问题就会变得简单了。
C++ 提供了一系列标准的异常,定义在 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:


说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一样自己定义一套异常继承体系。因为C++标准库设计的不够好用。
上面这么多的异常看起来眼花缭乱的,我们依旧可以使用多态的方式,只需要在main函数内构建一个父类对象,当子类内部发生异常返回的main函数,此时父类指针指向子类,实现多态,完成对子类what()方法的调用:
int main()
{
try{
vector<int> v(10, 5);
// 这里如果系统内存不够也会抛异常
v.reserve(1000000000);
// 这里越界会抛异常
v.at(10) = 100;
}
catch (const exception& e) // 这里捕获父类对象就可以
{
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
return 0;
}// 1.下面这段伪代码我们可以看到ConnnectSql中出错了,先返回给ServerStart,ServerStart再
返回给main函数,main函数再针对问题处理具体的错误。
// 2.如果是异常体系,不管是ConnnectSql还是ServerStart及调用函数出错,都不用检查,因为抛
出的异常异常会直接跳到main函数中catch捕获的地方,main函数直接处理错误。
int ConnnectSql()
{
// 用户名密码错误
if (...)
return 1;
// 权限不足
if (...)
return 2;
}
int ServerStart() {
if (int ret = ConnnectSql() < 0)
return ret;
int fd = socket()
if(fd < 0)
return errno;
}
int main()
{
if (ServerStart() < 0)
...
return 0;
}