作者:良知猶存
轉載授權以及圍觀:歡迎添加微信:Allen-Iverson-me-LYN
總述
在程序運行過程中經常會碰到一些問題,例如數組下標越界,除數爲零等,這些錯誤不過能被發現處理,則我們的代碼很有可能會導致程序崩潰。所以我們一般會針對可能導致程序崩潰的錯誤進行預測,C與C++都可以做。
但是C的判斷代碼要和相關函數執行的位置緊鄰,甚至要緊密的耦合。而C++引入了錯誤處理機制,使得執行程序與錯誤檢測的代碼可以分離開,這樣我們就可以安心的在單獨的寫代碼,多次調用某個函數,而僅在某一處編寫錯誤處理的代碼即可。
異常提供了一種轉移程序控制權的方式,涉及到C++異常處理的幾個關鍵詞有:
-
throw :當問題出現時,程序會拋出一個異常的標誌,這個拋出異常的動作就是由throw關鍵詞完成的。
-
catch:在我們處理問題的地方,通過異常處理程序捕獲異常。catch關鍵字用於捕獲異常。
-
try: try塊中的代碼標識將被激活的特定異常。它後面通常跟着一個或多個catch塊。
一、throw
拋出異常
使用 throw 語句在代碼塊中的任何地方拋出異常。throw 語句的操作數可以是任意的表達式,表達式的結果的類型決定了拋出的異常的類型。可以拋出變量也可以拋出函數
void C(int i)
{
int a =1;
double b =1.2;
float c = 1.3;
if(i ==0)
{
cout<<"in C ,it is OK"<<endl;
}
else if(i==1)
{
throw a;
}
else if(i==2)
{
throw b;
}
else if(i==3)
{
throw c;
}
else if(i==4)
{
throw Myexception();
}
else if(i==5)
{
throw MySubexception();
}
}
二、try與catch
捕獲異常
catch 塊跟在 try 塊後面,用於捕獲異常。我們可以指定想要捕捉的異常類型,這是由 catch 關鍵字後的括號內的異常聲明決定的。
void A(int i)
{
try{
B(i);
}catch(int t)
{
cout<<"catch int excepting "<<t<<endl;
}catch(double d)
{
cout<<"catch double excepting "<<d<<endl;
}catch(MySubexception &e){
e.waht();
}catch(Myexception &e){
e.waht();
}
catch(...)
{
cout<<"catch other excepting "<<endl;
}
}
如果你想讓 catch 塊能夠處理 try 塊拋出的任何類型的異常,則必須在異常聲明的括號內使用省略號 ...,如下所示:
catch(...)
{
cout<<"catch other excepting "<<endl;
}
哪段代碼可能發生錯誤,就把代碼放入try中,catch進行捕捉。發生的代碼片段用throw命令進行定義錯誤代碼。
而一旦發生異常,中斷程序執行,直接進入catch捕獲。捕獲的時候,先捕獲小範圍的,後捕獲大範圍的。
三、測試示例
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
/*通過throw命令 拋出整型 浮點等,類與派生類,然後進行catch*/
using namespace std;
class Myexception{
public:
void waht(void){cout<<"this is Myexception"<<endl;}
};
class MySubexception :public Myexception{
public:
void waht(void){cout<<"this is MySubexception"<<endl;}
};
void C(int i)
{
int a =1;
double b =1.2;
float c = 1.3;
if(i ==0)
{
cout<<"in C ,it is OK"<<endl;
}
else if(i==1)
{
throw a;
}
else if(i==2)
{
throw b;
}
else if(i==3)
{
throw c;
}
else if(i==4)
{
throw Myexception();
}
else if(i==5)
{
throw MySubexception();
}
}
void B(int i)
{
cout<<"call C..."<<endl;
C(i);
cout<<"After call C..."<<endl;
}
void A(int i)
{
try{
B(i);
}catch(int t)
{
cout<<"catch int excepting "<<t<<endl;
}catch(double d)
{
cout<<"catch double excepting "<<d<<endl;
}catch(MySubexception &e){
e.waht();
}catch(Myexception &e){
e.waht();
}
catch(...)
{
cout<<"catch other excepting "<<endl;
}
}
int main(int argc,char** argv)
{
int i;
if(argc !=2)
{
cout<<"Usage: "<<endl;
cout<<argv[0]<<" <0|1|2|3> "<<endl;
return -1;
}
i = strtoul(argv[1],NULL,0);/*轉化爲整型*/
A(i);
return 0;
}
這就是我分享的C++的異常處理,裏面代碼是實踐過的,如果大家有什麼更好的思路,歡迎分享交流哈。
更多分享,掃碼關注我
微信:Allen-Iverson-me-LYN