一、C语言异常处理的缺陷
1.错误码不好设置,比如:除0操作,就不好返回错误码。如果返回一个数字,可能会有两层含义,是错误,还是结果呢。一般我们会在参数加一个输出型参数返回结果,再规定成功和失败返回的数字。
2.需要程序员去查找错误码对应的含义。比如:很多系统接口函数都是把错误码放到全局变量errno中,表示错误。
3.终止程序。比如:发生越界,除0,内存错误等,会直接终止程序,并不能明确知道是什么错误。用户难以接收。
C++针对上面的不足,引入了异常的概念,不会终止程序,并且会将错误信息详细介绍。
int test(){
int a = 0;
int b = 0;
cin >> a >> b;
if (b == 0){
throw bad_exception("除0错误");//抛出异常
}
return a / b;
}
int main(){
try{
cout << test() << endl;//可能会出现异常代码
}
catch (const exception& e){
cout << e.what() << endl;//捕获异常
}
system("pause");
return 0;
}
该程序不会直接终止,而是会报错是“除0错误”
二、C++异常概念
throw:当问题出现,程序抛出一个异常。抛异常使用throw关键字完成。
catch:用于捕捉异常。catch(...)可以捕获任意类型的异常,主要时用来捕获没有显示捕获类型的异常。相当于条件判断中的else。
try:try中包含会出现异常的代码或者函数。后面通常会跟一个或者多个catch块
try
{
// 保护的标识代码
}
catch( ExceptionName e1 )
{
// catch 块
}
catch( ExceptionName e2 )
{
// catch 块
}
catch( ExceptionName eN )
{
// catch 块
}
注意:可以抛出任意类型的对象。抛出的异常必须捕获。try要和catch匹配使用,catch里的内容抛出异常时才执行,没有异常,不执行
三、异常的使用
3.1、异常的抛出和捕获
异常的抛出和捕获原则:
1、异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码
2、被选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。
3、抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成 一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回)
4、catch(…)可以捕获任意类型的异常,问题是不知道异常错误是什么。
5、实际中抛出和捕获的类型不一定类型完全匹配,可以抛出派生类对象,使用基类来捕获,这个在实际生活中很实用。主要原因是:派生类可以赋值给基类
异常的匹配规则:
1.首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch 的地方进行处理。
2. 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
3. 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的catch子句的 过程称为栈展开。所以实际中我们最后都要加一个catch(…)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。
4. 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行
#include<iostream>
#include<string>
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;
}
catch(...)
{
cout<<"Unknow exception"<<endl;
}
return 0;
}
运行结果:1 0Division by zero condition!
3.2、异常的重新抛出
#include<iostream>
#include<string>
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()
{
//这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
//所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再
//重新抛出去
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;
}
int main()
{
try{
Func();
}
catch(const char* errmsg)
{
cout << errmsg<<endl;
}
return 0;
}
3.3、异常安全
1.构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有 完全初始化 。
2.析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)
3.C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和 unlock之间抛出了异常导致死锁,C++经常使用RAII(智能指针)来解决以上问题。
3.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;
四、自定义异常体系
基类可以相当于是一个框架,派生类是具体的异常。然后去具体实现异常的内容,然后抛异常只需要抛派生类,捕捉异常只需要捕捉基类即可。
下面是一个简单的实现:
//基类
//异常
class Exception{
public:
Exception(const char* str = nullptr, int id = 0)
:_errmsg(str)
, _id(id)
{}
virtual void what()const = 0;
protected:
string _errmsg;//错误信息
int _id;//错误码
};
//派生类
//数据库异常
class SqlException :public Exception{
public:
SqlException(const char *str = nullptr, int id = 1)
:Exception(str, id)
{}
virtual void what()const{
cout << "error msg:" << _errmsg << endl;
cout << "error id:" << _id << endl;
}
};
//网络异常
class HttpException :public Exception{
public:
HttpException(const char *str = nullptr, int id = 2)
:Exception(str, id)
{}
virtual void what()const{
cout << "error msg:" << _errmsg << endl;
cout << "error id:" << _id << endl;
}
};
//缓存异常
class CacheException :public Exception{
public:
CacheException(const char *str = nullptr, int id = 3)
:Exception(str, id)
{}
virtual void what()const{
cout << "error msg:" << _errmsg << endl;
cout<< "error id:" << _id << endl;
}
};
void test(){
//当网络连接失败,抛出这个异常即可
//throw HttpException("Http fail", 2);
//当缓存错误
//throw CacheException("Cache error", 3);
//当数据库错误
throw SqlException("Sql error", 4);
}
int main(){
try{
test();
}
//用基类捕捉即可
catch (const Exception& a){
a.what();
}
catch (...){
cout << "unknow exception" << endl;
}
system("pause");
return 0;
}
五、C++标准库的异常体系
下面是对上面层次结构中出现的每个异常的说明:
unsigned short test(){
unsigned short a = 0;
unsigned short b = 0;
cin >> a >> b;
if (a + b > 65535 ){
//c++标准库中的异常类
throw overflow_error("overflow");
}
return a + b;
}
int main(){
try{
printf("%d\n", test());
}
//用基类捕捉
catch (const exception& a){
cout << a.what() << endl;
}
catch (...){
cout << "unknow exception" << endl;
}
system("pause");
return 0;
}
六、C++异常的优缺点
6.1、C++异常的优点:
总而言之,跟好的返回和描述错误信息,更好定位。针对某些错误,不需要终止程序。
6.2、C++异常的缺点:
总结:异常的使用利大于弊。异常时面向对象语言处理错误的方式,鼓励使用。