目录
前言:
在C语言里面,报错的方式往往是返回错误码,比如error1什么的,那么这个时候就需要程序员对照错误码的数字查找对应的错误,还有一种方式是直接终止程序,就像assert一样,所以有时候assert也成为暴力检查,那么可能有同学会觉得,这报错也没啥问题呀,但是,这里举个样例:
前几天是七夕节,你给你的女神发消息,结果发现人给你删了,欸,发消息这个动作,就失败了,系统应该报错,但是微信的操作不是直接终止掉你的整个微信吧?是返回一个红色感叹号,或者是尝试多发几次,这种方式比直接终止掉微信好多了,这就是C++的处理方式。
1 异常概念
除法函数,被除数为0的时候,就应该报错,所以我们可以理解为异常是一种处理错误行为的行为,抛异常之后,我们可以在抛出的异常里面选择抛出什么类型,以便提供更直观的信息,那么如何正确的抛异常呢?
我们首先要了解的是,抛异常使用的三个关键字:
throw:触发异常的检查条件之后,抛异常。
try:try的域里面用来检测异常,即里面可能激活某种异常,后面一般跟着多个catch代码块
catch:用来尝试捕捉异常,异常的最终归宿,捕获异常之后执行的行为都是在该处进行。
2 异常的使用
首先,我们要了解异常的抛出和使用规则:
1 异常抛出的是个对象,比如int char或者是自定义类型,用catch进行捕捉,所以catch里面也是像函数接受参数一样,需要类型等。
2 异常抛出的对象因为在其他栈帧里面,所以返回的是个局部对象,就相当于传值返回,所以会进行拷贝,拷贝的临时对象被捕捉之后就会销毁。
3 catch(...)代表捕捉的是未知异常,因为catch部分都没有成功捕捉,所以就要一个来接受,不能抛异常了但是没有捕捉到,可以说catch(...)是最后一道防线。
4 抛出的派生类对象可以用基类对象进行捕捉。
我们先来使用前三个规则:
int Division(int a, int b)
{
if (b == 0)
{
string str = "被除数为0";
throw str;
}
else if(b < 0)
{
throw 1;
}
else
{
return a / b;
}
}
int main()
{
int a = 0, b = 0;
while (1)
{
cin >> a >> b;
try
{
Division(a, b);
}
catch (const string& str)
{
cout << str << endl;
}
catch (...)
{
cout << "捕捉未知异常" << endl;
}
}
return 0;
}
这是基本情况,一是当b为0的时候,抛出的异常对象为string,所以我们使用string来捕捉,在catch里面就选择处理异常的方式,这里我们就进行打印就可以了。
那么,比如微信,发消息的时候,网络问题,第一次没发出去,就捕获了异常,那么可能就会尝试多发几次,当发送的次数上限了,就不会发送了,这也是一种处理异常的方式。
那么可以看到,在catch部分,没有捕获int类型的代码块,所以这里是catch(...)来捕捉。
这是基本使用,然后来看看进阶的使用,使用之前,我们了解一下栈展开的原则:
throw异常时候首先检查是不是在try里面,是的话再找对应的catch,但是如果是多个函数调用,该函数栈帧里面没有对用的catch,就会返回到上一层函数栈帧找catch,所以匹配catch的时候,总是会匹配距离最近的catch。如果到达了main函数的函数栈帧依旧没有,就会终止程序。
这个过程称为栈展开。
看一段代码:
void Division(int a, int b)
{
if (b == 0)
{
string str = "被除数为0";
throw str;
}
else if(b < 0)
{
throw 1;
}
else
{
cout << a / b << endl;
}
}
void Func()
{
int a = 0, b = 2;
cin >> a >> b;
Division(a, b);
}
int main()
{
while (1)
{
try
{
Func();
}
catch (const string& str)
{
cout << str << endl;
}
catch (...)
{
cout << "捕捉未知异常" << endl;
}
}
return 0;
}
这段代码就是典型的栈展开的代码,Func里面调用了除法函数,除法函数抛异常之后,在本函数栈帧里面没有发现对应的catch,然后往上走,发现Func里面也没有对应的catch,最后到了main函数里面,有对应的catch,这时捕获就被成功捕获了。
这里看一段代码,较为接近实际情况的:
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 = "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 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 = '张三'");
}
}
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)
{
this_thread::sleep_for(chrono::seconds(1));
try {
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 多态
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
异常使用一个专门的类,其他类继承该类,无非就是多了异常的错误码和id,然后抛异常的时候选择加上不同的信息,使信息更加具体,然后插入了多态的使用,利用了虚基表的指针呀什么的,捕获最终都是使用的父类对象来捕捉,也算是使用了子类可以给基类赋值。
3 异常的安全问题
不难发现,一旦触发了异常的条件,那么就会抛异常,本函数的后面的代码就不会执行了,这个问题就十分严重了,比如:
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 (...)
{
throw;
}
// ...
cout << "delete []" << array << endl;
delete[] array;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
return 0;
}
一共有两个部分捕捉异常,Func里面捕捉了一次,捕捉到了,那么将这个异常继续交给外面的处理,这里throw的写法是捕捉到了什么的异常就抛出什么异常,此时,原本是要析构开辟的空间的,但是因为抛异常了,就没有走到那一步去,哦豁了就。
这里会造成的问题就是,内存泄漏,因为C++没有自动回收资源,所以这个问题需要额外注意。
正确写法是:
void Func()
{
int* array = new int[10];
try {
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (...)
{
cout << "delete []" << array << endl;
delete[] array;
throw;
}
// ...
cout << "delete []" << array << endl;
delete[] array;
}
抛异常里面套一层,但是这样写实在是有点麻烦,所以一般异常都是交给最外层的处理,不然很容易造成内存泄漏的问题。
现在再来看一个内存泄漏的问题:
void Func()
{
int* p1 = new int[1000000000];
int* p2 = new int[1000000000];
int* p3 = new int[1000000000];
int* p4 = new int[1000000000];
int* p5 = new int[1000000000];
int* p6 = new int[1000000000];
int* p7 = new int[1000000000];
int* p8 = new int[1000000000];
int* p9 = new int[1000000000];
int* p10 = new int[1000000000];
int* p21 = new int[1000000000];
int* p22 = new int[1000000000];
int* p23 = new int[1000000000];
int* p24 = new int[1000000000];
int* p25 = new int[1000000000];
int* p26 = new int[1000000000];
int* p27 = new int[1000000000];
try
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl; // throw
}
catch (...)
{
delete[] p1;
cout << "delete:" << p1 << endl;
delete[] p2;
cout << "delete:" << p2 << endl;
throw;
}
delete[] p1;
cout << "delete:" << p1 << endl;
delete[] p2;
cout << "delete:" << p2 << endl;
}
int main()
{
try
{
Func();
}
catch (...)
{
//...
}
return 0;
}
猜猜为什么把new的空间开的那么大?这个点可能有点遗忘了,因为new的组成可以说是malloc + 初始化 + 抛异常。
没想到吧,new如果空间开多了,直接就跳出去了,这个时候前面开的空间就没有释放,内存泄漏一下就来了。
解决方法是什么呢,如下:
void Func()
{
int* p1 = new int[10];
int* p2 = nullptr;
try
{
p2 = new int[20];
try
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl; // throw
}
catch (...)
{
delete[] p1;
cout << "delete:" << p1 << endl;
delete[] p2;
cout << "delete:" << p2 << endl;
throw; // 捕获什么抛出什么
}
}
catch (...)
{
delete[] p1;
cout << "delete:" << p1 << endl;
throw;
}
delete[] p1;
cout << "delete:" << p1 << endl;
delete[] p2;
cout << "delete:" << p2 << endl;
}
如果p1抛异常了就直接出去就完事了,此时就要检查p2有没有抛异常了。但是如果new多了,不可能每一层都要套吧,那不得给人整进去,所以真正的解决方法呢在智能指针那里,下一篇文章会介绍。
有了这个的经验,我们就不应该在构造函数或者是析构函数的时候使用异常,要不然就是没有初始化完成,要么就是析构没有完成,两个都是致命的。
4 异常规范
// 这里表示这个函数会抛出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 delete (std::size_t size, void* ptr) throw();
// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;
在C++98里面常用的抛异常是上面三个,类型全写,或者只会抛出谁的异常,或者是确定不会抛出,在C++11里面就觉得太麻烦了。
所以现在引入noexcept关键字,表示不会抛异常,在许多库函数里面都有体现。
当然了,C++的异常体系并不完善,笔者这里学的不精,没有评头论足的资格,大家想要了解可以自行了解一下C++的异常体系。
感谢阅读!