传统的错误处理机制:
实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误。
异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。
如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。使用 try/catch 语句的语法如下所示:
try
{
// 保护的标识代码
}
catch( ExceptionName e1 )
{
// catch 块
}
catch( ExceptionName e2 )
{
// catch 块
}
catch( ExceptionName eN )
{
// catch 块
}
异常的抛出和匹配原则:
在函数调用链中异常栈展开匹配原则:
实验代码:
#include
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 Func1()
{
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
int main()
{
try
{
Func1();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "unknown error" << endl;
}
return 0;
}
实验结果:
有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。或者在抛异常之前程序申请资源或者打开了文件,但是在抛异常之后退出当前栈,导致资源没有被释放,文件没有被关闭,这就需要在当前栈捕捉异常再重新抛出。
实验代码:
double Division(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
throw "Division by zero condition!";
else
return ((double)a / (double)b);
}
void Func1()
{
int* ptr = new int[10];
try {
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (...) {
cout << "delete: " << ptr << endl;
delete[] ptr;
throw; // 异常重新抛出
}
}
int main()
{
try
{
Func1();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "unknown error" << endl;
}
return 0;
}
实验结果:
// 表示这个函数会抛出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();
在实际使用中,我们会自定义异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者没有办法识别异常是从哪一个业务层抛出的,所以实际中都会定义一套继承的规范体系。这样大家抛出的都是继承的派生类对象,捕获一个基类就可以。
下面我们模拟通过基类对象捕捉各个应用层的派生类异常对象:
class Execption
{
public:
Execption(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{}
virtual string what() const
{
return _errmsg;
}
protected:
string _errmsg;
int _id;
};
class HttpServerExecption : public Execption
{
public:
HttpServerExecption(const string& errmsg, int id, string type)
:Execption(errmsg, id)
, _type(type)
{}
virtual string what() const
{
string errmsg;
errmsg += "HttpServerException: ";
errmsg += _type;
errmsg += ":";
errmsg += _errmsg;
return errmsg;
}
private:
string _type;
};
class CacheExecption : public Execption
{
public:
CacheExecption(const string& errmsg, int id)
:Execption(errmsg, id)
{}
virtual string what() const
{
string errmsg;
errmsg += "CacheException: ";
errmsg += _errmsg;
return errmsg;
}
};
class SqlExecption : public Execption
{
public:
SqlExecption(const string& errmsg, int id, string sql)
:Execption(errmsg, id)
, _sql(sql)
{}
virtual string what() const
{
string errmsg;
errmsg += "SqlException: ";
errmsg += _errmsg;
errmsg += " -> ";
errmsg += _sql;
return errmsg;
}
private:
string _sql;
};
void SqlMgr()
{
srand(time(0));
if (rand() % 7 == 0) {
throw SqlExecption("权限不足", 100, "select * from table where name='jack'");
}
}
void CacheMgr()
{
srand(time(0));
if (rand() % 5 == 0) {
throw CacheExecption("权限不足", 100);
}
else if (rand() % 6 == 0) {
throw CacheExecption("数据不存在", 101);
}
SqlMgr();
}
void HttpServer()
{
srand(time(0));
if (rand() % 3 == 0) {
throw HttpServerExecption("请求资源不存在", 100, "get");
}
else if (rand() % 4 == 0) {
throw HttpServerExecption("权限不足", 200, "post");
}
CacheMgr();
}
void ServerStart()
{
while (true) {
this_thread::sleep_for(chrono::seconds(1));
try {
HttpServer();
}
catch (const Execption& e) {
cout << e.what() << endl;
}
catch (...) {
cout << "Unknown error" << endl;
}
}
}
int main()
{
ServerStart();
return 0;
}
实验结果:
C++ 提供了一系列标准的异常,定义中,我们可以在程序中使用这些标准的异常。它们是以父子类层次结构组织起来的,如下所示:
C++异常的优点:
C++异常的缺点: