C++异常是C++编程语言中用于处理运行时错误的一种机制。它允许程序在检测到无法处理的错误条件时,通过抛出异常(使用throw关键字)来跳出正常的执行流程,并立即跳转到与该异常类型相匹配的catch代码块中进行处理。
比如在C语言中我们学过strerror
函数可以把参数部分错误码对应的错误信息的字符串地址返回来。
C语言程序启动的时候就会使用一个全局的变量errno
来记录程序当前的错误码,只不过程序启动的时候errno
是0,表示没有错误,当我们在使用标准库中的函数的时候发生了某种错误,就会将对应的错误码存放在errno
中,而一个错误码的数字是整数很难理解是什么意思,所以每一个错误码都是有对应的错误信息的,strerror
函数就可以将错误码对应的错误信息字符串的地址返回来。整数0~10对应的错误信息如下:
C语言中获取错误信息需要单独调相关的函数,C++期望能直接获得一个错误对象,这个对象中包含比较全面的错误信息。异常是一种处理错误的方式,当一个函数出现自己无法处理的错误时抛出这个异常,让函数的直接或间接调用者处理这个错误。
throw
抛出一个异常,这个异常可以是任意类型catch
捕获异常,catch
可以有多个catch
块,后面通常跟着一个或多个catch
块异常处理机制提供了一种处理运行时错误的方法,使得程序能够在遇到错误时优雅地恢复或终止,而不是直接崩溃。
| 异常的抛出和匹配原则
catch
的处理代码,该对象在匹配catch
的过程中不会有任何隐式类型转换catch
以后销毁catch(...)
可以捕获任意类型的异常,只是不知道异常错误是什么| 在函数调用链中异常栈展开匹配原则
throw
本身是否在try
块内部,如果是再查找匹配的catch
语句catch
则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch,也就是说catch
语句正常流不会进去catch(...)
来捕获任意类型的异常catch
子句并处理以后,会继续沿着catch子句后面继续执行函数调用链展开过程中捕获异常看似是从抛出到捕获直接跳到匹配的
catch
语句,实际经过的函数都会正常结束,如果函数中有对象等也会正常调用析构处理干净。
有可能单个的catch
不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch
则可以通过重新抛出将异常传递给更上层的函数进行处理。
比如:有时在处理异常前有资源需要释放,那就要先释放掉资源再将异常重新抛出:
//...
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;
}
//...
catch(...)
不是为了处理异常,而是释放资源,捕到什么抛什么如果new
了多个对象如何处理?
我们知道new
在出现错误时也会抛异常,在上面的情况中,如果在new
第二个对象时抛出异常,那么第一个对象就得不到释放,所以当需要new
多个对象时,后面的new
代码都要放到try
块中进行保护。
//...
int* array1 = new int[10];
try
{
int* array2 = new int[10];
}
//...
这样比较麻烦,不过不用担心,对于类似这种情况更好的解决方案是下篇文章介绍的智能指针。
new
和delete
中抛出了异常,导致内存泄漏,在lock
和unlock
之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题,关于RAII在下篇智能指针中介绍throw
(类型),列出这个函数可能抛出的所有异常类型throw()
,表示函数不抛异常,C++11中新增关键字noexcept
,表示不抛异常noexcept
会影响异常的正常捕获,因此确定不会抛异常才能加noexcept
// 这里表示这个函数会抛出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;
实际中都会定义一套继承的规范体系,这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了。继承基类,在派生类中重写包含错误信息的相关虚函数实现多态,哪个派生类抛出异常,最后由基类接收,指向谁调用谁。
例如:
// 服务器开发中通常使用的异常继承体系
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{}
virtual string what() const
{
return _errmsg;
}
protected:
string _errmsg;//错误信息
int _id;//错误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)
{
this_thread::sleep_for(chrono::seconds(1));
try {
HttpServer();
}
catch (const Exception& e) // 这里捕获父类对象就可以
{
// 多态
cout << e.what() << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
}
return 0;
}
C++ 提供了一系列标准的异常,定义在std::exception
中,我们可以在程序中使用这些标准的异常,它们是以父子类层次结构组织起来的。
| 优点:
T& operator
这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误| 缺点:
func() throw();
的方式规范化总体来说异常还是利大于弊,合理地使用异常处理可以提高代码的健壮性和可读性,但滥用或不当使用则可能导致代码变得复杂且难以维护。
本篇文章的分享就到这里了,如果您觉得在本文有所收获,还请留下您的三连支持哦~