前言
? ? ? ? 上文我們學習到了C++11中類的新功能【C++11】類的新功能-CSDN博客
????????本文我們來學習C++下一個新語法:異常
1.異常的概念
? ? ? ? 異常的處理機制允許程序在運行時就出現的問題進行相應的處理。異常可以使得我們將問題的發現和問題的解決分開,程序的一部分負責檢測,而另一部分負責處理,檢測環節無需過多的細節。
? ? ? ? 當發生錯誤時,C語言主要通過錯誤碼的形式處理錯誤,錯誤碼本質是將不同的錯誤信息進行編號,拿到錯誤碼我們還需要進行查詢才能得知具體是什么錯誤,比較麻煩。而異常則是拋出一個對象,這個對象可以涵蓋對于這個錯誤的各種信息。
2.異常的拋出和捕獲
? ? ? ? 當程序出現問題時,我們將會通過【throw】拋出一個對象來引發一個異常,該對象的類型以及當前的位置決定了由哪個catch來處理。
? ? ? ? 被選中的catch是調用鏈中與給對象類型匹配且離拋出位置最近的那一個。根據拋出異常對象的類型和內容,程序的拋出異常部分會告知到底發生了什么錯誤。
? ? ? ? 當throw執行時,thorw后面的代碼將不再執行,就像break一樣直接跳出。程序的執行從throw的位置直接跳到匹配的catch位置,catch可能在同一個函數中,有可能在調用鏈的其他函數中。這里有兩個注意點:1.沿著調用鏈的函數可能會提前退出 ,2.一旦程序開始執行拋異常,沿著調用鏈創建的對象都將銷毀
? ? ? ? 拋出異常對象后,會產生一個異常對象的臨時對象,因為拋出的異常可能的局部對象。這個臨時對象會在catch語句后銷毀。
3.棧展開
? ? ? ? 拋異常后,程序會暫停當前的執行,開始尋找與之匹配的catch子句。首先檢查throw本身是否在try內部,如果在則查找有沒有匹配的catch語句,如果匹配就跳到catch是位置進行處理。
? ? ? ? 如果不匹配或者沒有try內部,則退出當前函數,繼續在外層調用函數鏈中查找,上述過程被稱為棧展開。
? ? ? ? 如果一直查找到main函數,依然沒有匹配的catch語句,那么程序就會調用標準庫的terminate函數終止程序。
? ? ? ? 如果在后續的查找過程中匹配到了相應的catch語句,那么就執行catch語句以及下面的代碼。
#include<iostream>
#include<string>
using namespace std;double Divide(int a, int b)
{try{//當b為0時拋出異常if (b == 0){string s("除數為0!");throw s;}else{return (double)a / b;}}catch(int errid) //拋異常時,類型不匹配。結束當前函數{cout << errid << endl;}
}void Func()
{int len, time;cin >> len >> time;try{cout << Divide(len, time) << endl;}catch (string errid)//類型匹配,直接跳到這里執行代碼{cout << errid << endl;cout << __FUNCTION__ << ":" << __LINE__ << endl;}}int main()
{while(1){try{Func();}catch (string errid)//類型匹配,但只會跳到最近的catch進行匹配{cout << errid << endl;cout << __FUNCTION__ << ":" << __LINE__ << endl;}}
}
//如果拋異常時,所有catch都不匹配就會報錯,程序停止。
4.查找匹配的處理代碼
? ? ? ? 一般情況下拋出的對象類型要和catch的接收類型完全一樣,如果有多個catch與之匹配,會匹配其最近的catch。
? ? ? ? 但是也又特殊情況,允許從非常量向常量的類型轉化,也是就權限縮小。允許數組轉換成指向數組的指針,允許函數轉換成函數指針;允許派生類轉換為基類,這個在實踐中非常常用,一般拋異常都是用這個設計的。
? ? ? ? 拋異常的匹配如果到了main函數仍然匹配不上,就會報錯,程序停止。但是一般來說不是發生嚴重的錯誤,我們是不期望程序停止的,所以在main函數的最后我們一般會使用 catch(...),它可以捕捉任意類型的異常,但是并不能知道具體的異常是什么。
????????通過繼承基類實現不同類型是異常,為了統一捕捉在實踐中我們一般都是在main函數中使用catch,try一定要和從catch一起使用。
#include<iostream>
#include<thread>
using namespace std;
//每個異常模塊都是繼承Exception的派生類,每個異常模塊都可以添加自己的數據
//最后捕獲的時候,我們捕獲基類就可以了//不同的異常類型都通過繼承基類來實現
class Exception
{
public:Exception(const string& errmsg,int id):_errmsg(errmsg),_id(id){ }virtual string what() const{return _errmsg;}int getid() const{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){ }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 HttpException : public Exception
{
public:HttpException(const string& errmsg, int id, const string& type):Exception(errmsg, id), _type(type){}virtual 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 (const Exception& e) //派生類可以向基類進行轉換,這里用基類進行捕獲即可{cout << e.what() << endl;}catch (...)//為防止出現異常不匹配導致程序終止,使用 【...】 進行匹配{cout << "未知異常" << endl;}}
}
5.異常重新拋出
? ? ? ? 有時catch捕捉到一個異常后,需要對錯誤進行分類,對其中某一個錯誤進行特殊處理,而其他的異常要重新拋出給外層調用鏈處理。異常捕獲后,直接使用throw,就可以重新拋出。
#include<iostream>
#include<string>
#include<thread>
using namespace std;//以下程序模擬展示聊天時發送消息的情況
//若不是網絡信號導致無法發送,則拋出異常
//若是網絡信號不好時拋出異常,嘗試多次發送class Exception
{
public:Exception(const string& errmsg, int id):_errmsg(errmsg), _id(id){}virtual string what() const{return _errmsg;}int getid() const{return _id;}protected:string _errmsg;int _id;
};class HttpException : public Exception
{
public:HttpException(const string& errmsg, int id, const string& type):Exception(errmsg, id), _type(type){}virtual string what() const{string str = "HttpException:";str += _type;str += ":";str += _errmsg;return str;}
private:const string _type;
};void _SeedMsg(const string& s)
{if (rand() % 2 == 0){throw HttpException("網絡不穩定,發送失敗", 102, "put");}else if (rand() % 7 == 0){throw HttpException("對方不是你好友", 103, "put");}else{cout << "發送成功" << endl;}
}void SeedMsg(const string& s)
{for (int i = 0; i < 4; i++){try{_SeedMsg(s);}catch (Exception& e){if (e.getid() == 102){//重新嘗試if (i == 3){//網絡信號太差,不再過多嘗試,重新拋出throw;}cout << "開始第" << i + 1 << "次嘗試" << endl;}else{//異常重新拋出throw;}}}
}int main()
{srand(time(0));while(1){this_thread::sleep_for(chrono::seconds(1));try{SeedMsg("hello");}catch (Exception& e){cout << e.what() << endl;}}
}
6.異常安全問題
? ? ? ? 當執行throw語句時,throw后面的語句將不再執行。當執行throw這個語句要跳出這個函數去匹配catch,但是這個函數之前申請了空間。這就會造成內存泄漏。
? ? ? ? 出現這種情況就需要我們重新捕獲異常,釋放資源后再重新拋出。這種處理方式是不好的,下篇文章我會講到智能指針,使用智能指針來解決這個問題是更好的方法。
7.異常規范
? ? ? ? 對于用戶和編譯器而言,預先知道函數會不會拋異常是很有意義的,這有助于簡化調用函數的代碼。
? ? ? ? C++98中函數后面加 throw( ),表示不會拋異常。函數后面加 throw(類型1,類型2,....),表示可能會拋出異常,如果會拋出多個類型的異常,使用逗號隔開。
? ? ? ? C++11中表示方式會更簡便一些,函數后面加noexcept表示不會拋出異常。而函數后面什么都不加則表示可能會拋出異常。
? ? ? ? 不過很搞笑的是,如果一個函數后面加了noexcept,但是函數包含throw語句或者包含可能會拋異常的函數,編譯器會順利的編譯通過。但是當這個函數真正拋出異常時,程序會報錯停止。
? ? ? ? noexcept(函數調用表達式) 還可以作為一個運算符,去檢查函數是否可能會拋異常。如果不會拋異常返回true,如果可能會拋異常返回fasle