传统的错误处理机制:
异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。
如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。使用 try/catch 语句的语法如下所示:
try
{
// 保护的标识代码
}catch( ExceptionName e1 )
{
// catch 块
}catch( ExceptionName e2 )
{
// catch 块
}catch( ExceptionName eN )
{
// catch 块
}
异常的抛出和匹配原则
在函数调用链中异常栈展开匹配原则
#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) {//没有错误则跳过这个catch
cout << errmsg << endl;
}
return 0;
}
没有错误catch部分不会执行
throw时才会执行catch部分
如果进行了throw,并且catch时类型不匹配,那么就会出现错误:因为找不到能够匹配的catch,找不到则会终止程序(此例就涉及了权限的放大)
如果都匹配,那么就选择更近的一个。
如果在Func中也进行了try、catch,那么优先就会进入优先符合参数匹配的,并且catch之后的代码继续执行
异常捕获的作用
异常捕获之后可以正常执行,可以防止因代码运行错误造成的内存泄漏,就比如:把此处的try注释掉,其就会匹配下一个,而这部分delete的代码就不会被执行从而造成内存泄漏。
当然除了异常还有别的方法,通过智能指针的方式,智能指针就是用来处理这个的。(后续讲)
有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。
如果想将每一次异常都放在一起,形成一个日志,即统一捕获并进行处理,此时就利用了将异常重新抛出的方式。
对于大型项目,调试的作用微乎其微,因此需要通过记录日志的方式对代码进行维护。
#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* p1 = new int[10];
try
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (const char* errmsg)
{
cout << "delete " << p1 << endl;
delete[] p1;
throw errmsg; // 重新抛出
}
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl; //重新抛出之后就可以在这里进行统一处理。
}
return 0;
}
如果抛出的类型过多,就会需要很多个catch语句,因此为了防止这么麻烦,就可以传**…** ,这样就能够匹配任意类型。但缺点就是不知道是什么类型的对象,因此还需要再抛出一下,直接throw表示捕捉到什么就抛出什么,这实际上就是将一些需要处理的动作处理之后再进行捕获的方式。
#define _CRT_SECURE_NO_WARNINGS 1
#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* p1 = new int[10];
try
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (...)
{
//cout << errmsg << endl;
cout << "delete " << p1 << endl;
delete[] p1;
throw;// 重新抛出,捕获什么就抛出什么
}
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{//没有错误则跳过这个catch
cout << errmsg << endl;
}
catch (int errid)
{
cout << errid << endl;
}
return 0;
}
对于异常,如果不按照一定的规范,在函数调用函数的过程中,每个都存在try-catch语句的话,大概格式如下:
如果在A调用B,B调用C,C调用D的过程中没有抛异常,而在D中抛出异常(throw没写,上面只是格式)却由于类型不匹配或者其他原因没有捕获,那么此时发生异常的就不仅仅是D,A、B、C也都会相继抛出异常,因此,为了控制哪个函数抛异常,哪个函数不抛异常,抛什么类型的】异常,就产生了如下方法:
解决方法:
// 这里表示这个函数会抛出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;
注:vector的[]内部检查是断言,vector的at是抛异常。
实际使用中很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者基本就没办法玩了,所以实际中都会定义一套继承的规范体系。这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了。
// 服务器开发中通常使用的异常继承体系
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 = '张三'");
}
//throw "xxxxxx";
}
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);//单位:ms
try {
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 多态
cout << e.what() << endl;
}
catch (const CacheException& e)//上面匹配了,这里就不会匹配了
{
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
C++ 提供了一系列标准的异常,定义在 中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:
说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一样自己定义一套异常继承体系。因为C++标准库设计的不够好用。
代码实例:
#include<iostream>
#include<vector>
using namespace std;
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;
}
缺点:
总结: 异常总体而言,利大于弊,所以工程中我们还是鼓励使用异常的。另外OS的语言基本都是用异常处理错误。