目录
一、异常的概念以及使用
1.1、异常的概念
异常处理机制允许程序中独⽴开发的部分能够在运⾏时就出现的问题进⾏通信并做出相应的处理,
异常使得我们能够将问题的检测与解决问题的过程分开,程序的⼀部分负责检测问题的出现,然后
解决问题的任务传递给程序的另⼀部分,检测环节⽆须知道问题的处理模块的所有细节。
C语⾔主要通过错误码的形式处理错误,错误码本质就是对错误信息进⾏分类编号,拿到错误码以
后还要去查询错误信息,⽐较⿇烦。异常时抛出⼀个对象,这个对象可以函数更全⾯的各种信息。
1.2、异常的抛出和捕获
程序出现问题时,我们通过抛出(throw)⼀个对象来引发⼀个异常,该对象的类型以及当前的调⽤
链决定了应该由哪个catch的处理代码来处理该异常。
被选中的处理代码是调⽤链中与该对象类型匹配且离抛出异常位置最近的那⼀个。根据抛出对象的
类型和内容,程序的抛出异常部分告知异常处理部分到底发⽣了什么错误。
当throw执⾏时,throw后⾯的语句将不再被执⾏。程序的执⾏从throw位置跳到与之匹配的catch
模块,catch可能是同⼀函数中的⼀个局部的catch,也可能是调⽤链中另⼀个函数中的catch,控
制权从throw位置转移到了catch位置。这⾥还有两个重要的含义:1、沿着调⽤链的函数可能提早
退出。2、⼀旦程序开始执⾏异常处理程序,沿着调⽤链创建的对象都将销毁。
抛出异常对象后,会⽣成⼀个异常对象的拷⻉,因为抛出的异常对象可能是⼀个局部对象,所以会
⽣成⼀个拷⻉对象,这个拷⻉的对象会在catch⼦句后销毁。(这⾥的处理类似于函数的传值返
回)
1.3、栈展开
抛出异常后,程序暂停当前函数的执⾏,开始寻找与之匹配的catch⼦句,⾸先检查throw本⾝是否
在try块内部,如果在则查找匹配的catch语句,如果有匹配的,则跳到catch的地⽅进⾏处理。
如果当前函数中没有try/catch⼦句,或者有try/catch⼦句但是类型不匹配,则退出当前函数,继续
在外层调⽤函数链中查找,上述查找的catch过程被称为栈展开。
如果到达main函数,依旧没有找到匹配的catch⼦句,程序会调⽤标准库的
terminate
函数终⽌
程序。
如果找到匹配的catch⼦句处理后,catch⼦句代码会继续执⾏。
int Divide(int a, int b)
{
try
{
if (b == 0)
{
string str("Divide by zero condition!");
throw str;
}
else
{
return a / b;
}
}
catch (int errid)
{
cout << errid << endl;
}
return 0;
}
void Func()
{
int len, time;
cin >> len >> time;
try
{
Divide(len, time);
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
cout << __FUNCTION__ << ":" << __LINE__ << "行执行" << endl;
}
int main()
{
while (1)
{
try
{
Func();
}
catch(const string& errmsg)
{
cout << errmsg << endl;
}
}
return 0;
}

若是b为0,那么会throw抛异常,先在当前函数域找有无匹配的catch来匹配抛出异常对象的类型,但是这个函数里面的是int,继续在函数链中找,Divide里面也不匹配,编译器直接跳到main函数,匹配,那么打印异常信息;注意,throw之后Divide里面throw后面的都不会执行;当捕获异常时,若是不匹配那么这个不匹配的catch不会执行;
若是此时main函数里面也没有匹配的,会调用标准库中的terminate直接终止程序
1.4、查找匹配的处理代码
⼀般情况下抛出对象和catch是类型完全匹配的,如果有多个类型匹配的,就选择离他位置更近的
那个。
但是也有⼀些例外,允许从⾮常量向常量的类型转换,也就是权限缩⼩;允许数组转换成指向数组
元素类型的指针,函数被转换成指向函数的指针;允许从派⽣类向基类类型的转换,这个点⾮常实
⽤,实际中继承体系基本都是⽤这个⽅式设计的。
如果到main函数,异常仍旧没有被匹配就会终⽌程序,不是发⽣严重错误的情况下,我们是不期望程序终⽌的,所以⼀般main函数中最后都会使⽤catch(...),它可以捕获任意类型的异常,但是
不知道异常错误是什么。
举例派生类向基类转换的异常捕获:
class Exception
{
public:
Exception(const string& errmsg, int id)
:_errmsg(errmsg)
, _id(id)
{}
virtual const string what()const
{
return _errmsg;
}
int getid()
{
return _id;
}
protected:
string _errmsg;
int _id;
};
class SqlException :public Exception
{
public:
SqlException(const string& errmsg,int id,const string& sql)
:Exception(errmsg,id)
,_sql(sql)
{}
const 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)
{}
const string what()const
{
string str("CacheException:");
str += _errmsg;
return str;
}
};
class HttpException :public Exception
{
public:
HttpException(const string& errmsg,int id,const string& type)
:Exception(errmsg,id)
,_type(type)
{}
const string what()const
{
string str("HttpException:");
str += _type;
str += ":";
str += _errmsg;
return str;
}
private:
const string _type;
};
void SqlMgr()
{
if (rand() % 7 == 0)
{
throw SqlException("权限不足", 100, "select * from name = '张三'");
}
else
cout << "SqlMgr调用成功" << endl;
}
void CacheMgr()
{
if (rand() % 5 == 0)
{
throw CacheException("权限不足", 100);
}
else if (rand() % 6 == 0)
{
throw CacheException("数据不存在", 101);
}
else
cout << "CacheMgr调用成功" << endl;
SqlMgr();
}
void HttpServer()
{
if (rand() % 3 == 0)
{
throw HttpException("请求资源不存在", 100, "get");
}
else if (rand() % 4 == 0)
{
throw HttpException("权限不足", 101, "post");
}
else
{
cout << "HttpServer调用成功" << endl;
}
CacheMgr();
}
int main()
{
srand(time(0));
while (1)
{
this_thread::sleep_for(chrono::seconds(1));
try
{
HttpServer();
}
catch(Exception& obj)
{
cout << obj.what() << endl;
}
catch (...)
{
cout << "Unkown Exception!" << endl;
}
}
return 0;
}
sql、cache、http都继承了基类exception,并且用重写what形成多态,这个多态就是为了打印不同的异常信息的;
1.5、异常的重新抛出
有时catch到⼀个异常对象后,需要对错误进⾏分类,其中的某种异常错误需要进⾏特殊的处理,其他错误则重新抛出异常给外层调⽤链处理。捕获异常后需要重新抛出,直接 throw;
就可以把捕获的对象直接抛出。
也就是说有的异常需要特殊处理,在抛出这个异常的过程中,在调用链中捕获这个异常进行特殊处理,其他的异常被这个也捕获了就重新抛出,throw;若是这个特殊处理的异常没有处理成功也会重新抛出。
void _SendMsg(const string& Msg)
{
if (rand() % 2 == 0)
{
throw HttpException("网络不稳定,发送失败", 102, "put");
}
else if (rand() % 7 == 0)
{
throw HttpException("你已不是对方好友", 107, "put");
}
else
cout << "发送成功!" << endl;
}
void SendMsg(const string& Msg)
{
//网络不稳定的异常需要特殊处理,重新发送三次
//这里4次循环,是因为开始有一次
for (int i = 0; i < 4; i++)
{
try
{
_SendMsg(Msg);
break;//若是走到这里,说明发送成功,那么就结束捕获
}
catch (Exception& obj)
{
if (obj.getid() == 102)//网络不稳定的异常
{
if (i == 3)
throw;//重试三次,没有成功,网络太差直接重新抛出
cout << "开始第" << i + 1 << "次重试" << endl;
}
else
throw;//其他情况直接重新抛出;
}
}
}
int main()
{
srand(time(0));
while (1)
{
string str;
cin >> str;
try
{
SendMsg(str);
}
catch (Exception& obj)
{
cout << obj.what() << endl;
}
catch (...)
{
cout << "Unkown Exception!" << endl;
}
}
return 0;
}

1.6、异常安全问题
异常抛出后,后⾯的代码就不再执⾏,前⾯申请了资源(内存、锁等),后⾯进⾏释放,但是中间可
能会抛异常就会导致资源没有释放,这⾥由于异常就引发了资源泄漏,产⽣安全性的问题。中间我
们需要捕获异常,释放资源后⾯再重新抛出
其次析构函数中,如果抛出异常也要谨慎处理,⽐如析构函数要释放10个资源,释放到第5个时抛
出异常,则也需要捕获处理,否则后⾯的5个资源就没释放,也资源泄漏了。
1.7
int Divide(int a, int b)
{
if (b == 0)
{
throw "Divide by zero condition!";
}
else
{
return a / b;
}
}
void Func()
{
//中间调用链的某一部分申请了资源,需要在中间捕获释放资源
//否则,直接在main中处理异常,那么这里的资源没有释放造成内存泄漏的问题
int* arr = new int[10];
try
{
int len, time;
cin >> len >> time;
Divide(len, time);
}
catch (...)
{
//捕获异常释放资源
cout << "delete[]" << arr << endl;
delete[] arr;
throw;//重新抛出异常给外层处理
}
//没有异常情况
delete[] arr;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "Unkown Exception!" << endl;
}
return 0;
}
1.7、异常规范
对于用户和编译器而言,预先知道某个程序会不会抛出异常大有裨益,知道某个函数是否会抛出异
常有助于简化调用函数的代码。
C++98中函数参数列表的后⾯接throw(),表示函数不抛异常,函数参数列表的后⾯接throw(类型1,
类型2...)表示可能会抛出多种类型的异常,可能会抛出的类型⽤逗号分割。
C++98的⽅式这种⽅式过于复杂,实践中并不好⽤,C++11中进⾏了简化,函数参数列表后⾯加
noexcept表⽰不会抛出异常,啥都不加表⽰可能会抛出异常。
编译器并不会在编译时检查noexcept,也就是说如果⼀个函数⽤noexcept修饰了,但是同时⼜包
含了throw语句或者调⽤的函数可能会抛出异常,编译器还是会顺利编译通过的(有些编译器可能会
报个警告)。但是⼀个声明了noexcept的函数抛出了异常,程序会调⽤
terminate
终⽌程序。
noexcept(expression)还可以作为⼀个运算符去检测⼀个表达式是否会抛出异常,可能会则返回
false,不会就返回true。
//// C++98
//// 这⾥表⽰这个函数只会抛出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
//size_type size() const noexcept;
//iterator begin() noexcept;
//const_iterator begin() const noexcept;
double Divide(int a, int b) noexcept
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Division by zero condition!";
}
return (double)a / (double)b;
}
int main()
{
try
{
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (...)
{
cout << "Unkown Exception" << endl;
}
int i = 0;
cout << noexcept(Divide(1, 2)) << endl;
cout << noexcept(Divide(1, 0)) << endl;
cout << noexcept(++i) << endl;//输出001
return 0;
}
二、标准库的异常
https://legacy.cplusplus.com/reference/exception/exception/
C++标准库也定义了⼀套⾃⼰的⼀套异常继承体系库,基类是exception,所以我们⽇常写程序,需要在主函数捕获exception即可,要获取异常信息,调⽤what函数,what是⼀个虚函数,派⽣类可以重写。
407

被折叠的 条评论
为什么被折叠?



