主頁 > 後端開發 > c++中的例外處理

c++中的例外處理

2020-09-16 04:07:59 後端開發

 目錄

  1、 例外 與 Bug 的區別

  2、c++中的例外處理方式(try ... catch ...)

  3、自定義例外類的使用方式

  4、C++ 標準庫中的例外類

  5、try..catch 另類寫法 和  函式例外宣告/定義 throw()

 

1、 例外 與 Bug 的區別  

  “例外”是我們在程式開發中必須考慮的一些特殊情況,是程式運行時就可預料的執行分支(注:例外是不可避免的,如程式運行時產生除 0 的情況;打開的外部檔案不存在;陣列訪問的越界等等);

  “Bug”是程式的缺陷,是程式運行時不被預期的運行方式(注:Bug是人為的、可避免的;如使用野指標;堆陣列使用結束后未釋放等等);

  無論是“例外”還是“Bug”,都是程式正常運行程序中可能出現的意外情況,區別是“例外”可以捕獲,并做出合適的處理,“Bug"所帶來的后果是無法預測的,需要重寫相應的代碼,

2、c++中的例外處理方式(try ... catch ...)

 (1)基本語法

1 // 例外基本語法
2 try
3 {
4     // 可能產生例外的代碼,若發生例外,通過 throw 關鍵字拋出例外
5 }
6 catch(例外型別) // 例外捕獲,注(...)代表捕獲所有例外
7 {
8     // 處理例外的代碼,該例外由try陳述句塊產生
9 }

 (2)基本規則 

  1)同一個 try 陳述句可以跟上多個 catch 陳述句(在工程中,將可能產生例外的代碼放在 try 陳述句塊中,然后后面跟上多個 catch 陳述句);

  2)try 陳述句中通過 throw 關鍵字 可以拋出任何型別的例外(int、字串、物件等等); 

  3)catch 陳述句可以定義具體處理的例外型別,如 catch( int ) 只捕獲 int 型別例外, 但無法進一步獲取例外資訊;catch( int a ) 只捕獲 int 型別例外,可以進一步獲取例外資訊;

  4)不同型別的例外由不同的 catch 陳述句負責處理;

  5)catch(...) 用于處理所有型別的例外(只能放在所有 catch陳述句 的后面);

  6)任何例外都只能被捕獲(catch)一次;

  7)只要被 catch 捕獲一次,其它的 catch 就沒有捕獲機會了;

  8)throw 拋出例外的型別 與 catch 捕獲例外的型別  必須嚴格匹配(不能進行型別轉換);若匹配成功,則能夠捕獲該例外;否則捕獲失敗,程式停止執行,

    

  其實,為了更好的理解 例外拋出 和 例外捕獲 這兩個動作,我們可以將其想象成 函式呼叫,拋出例外好比是函式中實參,捕獲例外好比是函式中形參,只有當實參的型別 與 形參的型別嚴格匹配時,這次捕獲才能成功,為什么說想象成函式呼叫,而不是正真的函式呼叫呢?原因就是:函式呼叫時,用實參初始化形參時可以進行隱式的型別轉換;但是在例外捕獲時,必須嚴格匹配例外型別,  

(3)例外拋出(throw exception)的邏輯分析

  情況1:例外代碼沒有放到  try{ }  陳述句中,這也意味著沒有對應的 catch 陳述句,其實就是普通函式呼叫,若此時拋出例外(throw),則程式停止執行;

  情況2:例外代碼放到  try{ throw exception... }  陳述句中,這也意味著有對應的 catch 陳述句,則拋出例外時就會與 catch陳述句嚴格匹配;若匹配成功,則可以捕獲該例外,否則不能捕獲該例外,程式停止執行,

  throw 拋出例外后,在發生例外的函式中至上而下的嚴格匹配每一個 catch 陳述句捕獲的例外型別,來判斷是否能夠捕獲該例外;

   1) 若發生例外的函式中  能夠捕獲該例外,則程式接著往下執行;

   2) 若發生例外的函式中  不能捕獲該例外,則未被處理的例外會順著函式呼叫堆疊向上傳播,直到該例外被捕獲為止,否則程式將停止執行;

  總結:throw 拋出的例外必須被 對應的 catch 捕獲,否則程式將停止執行;

    

  通過上圖來說明例外拋出后的執行順序:

  1)在 函式 function3 中 拋出例外 throw 1;但是在 function3 中并不能捕獲該例外,則例外繼續向外層函式 function2 拋出

  2)在 函式 function2 中,例外依舊沒有被捕獲,則例外繼續向外層函式 function1 拋出;

  3)在 函式 function1 中,例外被 catch 捕獲和處理,然后程式繼續向下執行;

    注:若在 函式 function1 中,例外還是沒有被捕獲,則例外會一直向外層函式拋出,直到該例外被捕獲為止,否在程式停止執行, 

  代碼展示:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 double divide(double a, double b)
 7 {
 8     const double delta = 0.000000001;
 9     double ret = 0;
10 
11     if( !((-delta < b) && (b < delta)) )
12     {
13         ret = a / b;
14     }
15     else
16     {
17         throw "Divided by zero..."; 
18     }
19 
20     cout << "divide(double a, double b)" << endl;
21      
22     return ret;
23 }
24 
25 double ExceptionFunc()
26 {
27     double d = divide(2, 0);
28     
29     cout << "ExceptionFunc()" << endl;
30     
31     return d;
32 }
33 
34 int main(int argc, char *argv[])
35 {      
36     double d = ExceptionFunc();
37     
38     cout << "result = " << d << endl;
39 
40     return 0;
41 }
42 
43 /**
44  * 運行結果:
45  * terminate called after throwing an instance of 'char const*'
46  * Aborted (core dumped)
47  */
48  
49 /**
50  * 分析:
51  * throw "Divided by zero..."; 拋出例外后,divide(double a, double b) 函式不能捕獲該例外,則例外繼續拋給 ExceptionFunc();
52  * 在 ExceptionFunc() 中,也不能捕獲該例外,則例外繼續拋給 main();
53  * 在 main()中,也不能捕獲該例外,則程式停止執行,
54  */
情況1 :例外案列復現

  

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 double divide(double a, double b)
 7 {
 8     const double delta = 0.000000001;
 9     double ret = 0;
10     
11     try
12     {
13         if( !((-delta < b) && (b < delta)) )
14         {
15             ret = a / b;
16         }
17         else
18         {
19             throw "Divided by zero..."; 
20         }
21     }
22     catch(char const* s)  
23     {
24         cout << s << endl;
25     } 
26         
27     cout << "divide(double a, double b)" << endl;
28  
29     return ret;
30 }
31 
32 double ExceptionFunc()
33 {   
34     double d = divide(2, 0);
35     
36     cout << "ExceptionFunc()" << endl;
37     
38     return d;
39 }
40 
41 int main(int argc, char *argv[])
42 { 
43     ExceptionFunc();
44       
45     cout << "test end!" << endl;
46 
47     return 0;
48 }
49 
50 /**
51  * 運行結果:
52  * Divided by zero...
53  * divide(double a, double b)
54  * ExceptionFunc()
55  * test end!
56  */
57  
58 /**
59  * 分析:
60  * throw "Divided by zero..."; 拋出例外后,在divide(double a, double b) 中,例外被捕獲,則程式繼續向下執行;
61  *  catch(char const* s)    // throw "Divided by zero..."
62  *  {
63  *     cout << s << endl;
64  *  }   
65  *  cout << "divide(double a, double b)" << endl;
66  *
67  *  divide(2, 0); 函式呼叫結束,回傳到 ExceptionFunc() 中,
68  *  cout << "ExceptionFunc()" << endl;  
69  *   
70  *  ExceptionFunc()呼叫結束,回傳 main()中,繼續向下執行;
71  *  cout << "test end!" << endl;
72  */
情況2 :例外案列復現1

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 double divide(double a, double b)
 7 {
 8     const double delta = 0.000000001;
 9     double ret = 0;
10           
11     if( !((-delta < b) && (b < delta)) )
12     {
13         ret = a / b;
14     }
15     else
16     {
17         throw "Divided by zero..."; 
18     }
19 
20     cout << "divide(double a, double b)" << endl;
21 
22     return ret;
23 }
24 
25 double ExceptionFunc()
26 {
27     double d;
28     
29     try
30     {
31         d = divide(2, 0);
32             
33         cout << "d = " << d << endl;
34     }
35     catch(char const* s)
36     {
37         cout << s << endl;
38     }           
39     
40     cout << "ExceptionFunc()" << endl;
41     
42     return d;
43 }
44 
45 int main(int argc, char *argv[])
46 { 
47     ExceptionFunc();
48     
49     cout << "test end!" << endl;
50 
51     return 0;
52 }
53 
54 /**
55  * 運行結果:
56  * Divided by zero...
57  * ExceptionFunc()
58  * test end!
59  */
60  
61 /**
62  * 分析:
63  * throw "Divided by zero..."; 拋出例外后,divide(double a, double b) 函式不能捕獲該例外,則例外繼續拋給 ExceptionFunc();
64  * 在 ExceptionFunc() 中,例外被捕獲,則程式繼續向下執行;
65  *  catch(char const* s)    // throw "Divided by zero..."
66  *  {
67  *     cout << s << endl;
68  *  }   
69  *  cout << "ExceptionFunc()" << endl;     
70  *  ExceptionFunc()呼叫結束,回傳 main()中,繼續向下執行;
71  *  cout << "test end!" << endl;
72  */
情況2 :例外案列復現2

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 double divide(double a, double b)
 7 {
 8     const double delta = 0.000000001;
 9     double ret = 0;
10 
11     if( !((-delta < b) && (b < delta)) )
12     {
13         ret = a / b;
14     }
15     else
16     {
17         throw "Divided by zero..."; 
18     }
19  
20     cout << "divide(double a, double b)" << endl;
21 
22     return ret;
23 }
24 
25 double ExceptionFunc()
26 {
27     double d = divide(2, 0);
28     
29     cout << "ExceptionFunc()" << endl;
30     
31     return d;
32 }
33 
34 int main(int argc, char *argv[])
35 { 
36     try
37     {
38         double d = ExceptionFunc();
39             
40         cout << "d = " << d << endl;
41     }
42     catch(char const* s)
43     {
44         cout << s << endl;
45     }        
46     
47     cout << "test end!" << endl;
48 
49     return 0;
50 }
51 
52 /**
53  * 運行結果:
54  * Divided by zero...
55  * test end!
56  */
57  
58 /**
59  * 分析:
60  * throw "Divided by zero..."; 拋出例外后,divide(double a, double b) 函式不能捕獲該例外,則例外繼續拋給 ExceptionFunc();
61  * 在 ExceptionFunc() 中,也不能捕獲該例外,則例外繼續拋給 main();
62  * 在 main()中,例外與被捕獲,則程式繼續向下執行
63  *  catch(char const* s)    // throw "Divided by zero..."
64  *  {
65  *     cout << s << endl;
66  *  }   
67  *  cout << "test end!" << endl;     
68  */
情況2 :例外案列復現3

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void Demo1()
 7 {
 8     try
 9     {   
10         throw 2.0;
11     }
12     catch(char c)
13     {
14         cout << "catch(char c)" << endl;
15     }
16     catch(short c)
17     {
18         cout << "catch(short c)" << endl;
19     }
20     catch(double c)   // throw 2.0;
21     {
22         cout << "catch(double c)" << endl;
23     }
24     catch(...)   // 表示捕獲任意型別的例外
25     {
26         cout << "catch(...)" << endl;
27     }   
28 }
29 
30 void Demo2()
31 {
32     throw string("D.T.Software"); 
33 }
34 
35 int main(int argc, char *argv[])
36 {    
37     Demo1();
38     
39     try
40     {
41         Demo2();      
42     }
43     catch(char* s)
44     {
45         cout << "catch(char *s)" << endl;
46     }
47     catch(const char* cs)
48     {
49         cout << "catch(const char *cs)" << endl;
50     }
51     catch(string ss)    // throw string("D.T.Software"); 
52     {
53         cout << "catch(string ss)" << endl;
54     }  
55     
56     return 0;
57 }
58 /**
59  * 運行結果:
60  * catch(double c)
61  * catch(string ss)
62  */
63 
64 // 結論:例外型別嚴格匹配,(...)表示捕獲任意型別的例外
情況2 :多分支的例外捕獲

   總結:

  情況1:只拋出例外,沒有對應地例外捕獲;(  沒有 try ... catch ... 結構  )

  情況2:在try陳述句塊中拋出例外(直接在try陳述句塊中使用 throw 拋出例外;或者try陳述句塊中放入有例外的函式,間接地在函式中使用 throw 拋出例外),然后通過catch陳述句捕獲同型別的例外并進行例外處理;( 現象: 一個 try ... catch ... 結構 )

  那么現在我們考慮能不能在情況2的基礎上,將捕獲到例外繼續拋出呢?(在 catch 陳述句塊中重新拋出例外?)

  可以在 catch 陳述句中重新拋出例外,此時需要外層的 try ... catch ...捕獲這個例外;

  注:catch 陳述句中只拋出例外,什么也不做;當捕獲任意型別的例外時,直接使用 throw 就行,

  

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void Demo()
 7 {
 8     try
 9     {
10         throw 'c';
11     }
12     catch(int i)
13     {
14         cout << "Inner: catch(int i)" << endl;
15         throw i;
16     }
17     catch(...)
18     {
19         cout << "Inner: catch(...)" << endl;
20         throw;
21     }
22 }
23 
24 int main(int argc, char *argv[])
25 {
26     Demo();
27     
28     return 0;
29 }
30 
31 /**
32  * 運行結果:
33  * Inner: catch(...)
34  * terminate called after throwing an instance of 'char'
35  * Aborted (core dumped)
36  */
37  // 錯誤原因:例外重解釋之后,沒有被捕獲
例外的重新解釋案列(error)

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void Demo()
 7 {
 8     try
 9     {
10         try
11         {
12             throw 'c';
13         }
14         catch(int i)
15         {
16             cout << "Inner: catch(int i)" << endl;
17             throw i;
18         }
19         catch(...)
20         {
21             cout << "Inner: catch(...)" << endl;
22             throw;
23         }
24     }
25     catch(...)
26     {
27         cout << "Outer: catch(...)" << endl;
28     }
29 }
30 
31 int main(int argc, char *argv[])
32 {
33     Demo();
34     
35     return 0;
36 }
37 /**
38  * 運行結果:
39  * Inner: catch(...)
40  * Outer: catch(...)
41  */
例外的重新解釋案列

   為什么要在 catch 陳述句塊中重新拋出例外?

  在工程中,利用在 catch 陳述句塊中重新解釋例外并拋出這一特性,可以統一例外型別,(很晦澀,看下面解釋....)

  

  我們通過上圖來詳細說明這個情況:

  背景介紹:出于開發效率考慮,在工程開發中一般會基于第三方庫來開發,但是,第三方庫中的某些功能并不完善(可讀性差),此時就需要封裝第三方庫中的這個功能,

  在上圖中,由于第三方庫中 func()函式的例外型別是 int 型別,可讀性很差,不能夠直接通過例外結果知道該例外所代表的意思;基于這種情況,我們通過私有庫中的 MyFunc()函式對第三方庫中func()進行了封裝,使得 MyFunc()函式中的例外型別可以顯示更多的例外資訊(MyFunc() 函式中的例外型別是自定義型別,可以是字串、型別別等等),增強代碼的可讀性;為了將 func()中的例外型別 和 MyFunc() 中例外型別統一起來,我們可以在私有庫中的MyFunc() 函式中去捕獲第三方庫中的 func() 函式拋出的例外,然后根據捕獲到的例外重新解釋為我們想要的例外,這樣我們工程開發中所面對的例外型別就是一致的;接下來我們用代碼復現這個場景:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 /*
 7     假設:當前的函式是第三方庫中的函式,因此,我們無法修改源代碼
 8     
 9     函式名: void func(int i)
10     拋出例外的型別: int
11                         -1 ==》 引數例外
12                         -2 ==》 運行例外
13                         -3 ==》 超時例外
14 */
15 void func(int i)
16 {
17     if( i < 0 )
18     {
19         throw -1;
20     }
21     
22     if( i > 100 )
23     {
24         throw -2;
25     }
26     
27     if( i == 11 )
28     {
29         throw -3;
30     }
31     
32     cout << "Run func..." << endl;
33 }
34 
35 int main(int argc, char *argv[])
36 {
37     try
38     {
39         func(11);
40     }
41     catch(int i)
42     {
43         cout << "Exception Info: " << i << endl;
44     }
45     
46     return 0;
47 }
48 
49 /**
50  * 運行結果:
51  * Exception Info: -3
52  */
53  
54 // 例外顯示結果太簡單,當發生例外時,需要查詢技術檔案才能知道這兒的-3代表的意思,可讀性很差
模擬 第三方庫例外代碼案列

 

// 例外的重解釋,在 catch 陳述句中重新拋出例外

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 /*
 7     假設: 當前的函式式第三方庫中的函式,因此,我們無法修改源代碼
 8     
 9     函式名: void func(int i)
10     拋出例外的型別: int
11                         -1 ==》 引數例外
12                         -2 ==》 運行例外
13                         -3 ==》 超時例外
14 */
15 void func(int i)
16 {
17     if( i < 0 )
18     {
19         throw -1;
20     }
21     
22     if( i > 100 )
23     {
24         throw -2;
25     }
26     
27     if( i == 11 )
28     {
29         throw -3;
30     }
31     
32     cout << "Run func..." << endl;
33 }
34 
35 /* 不能修改 func() 函式,則我們定義 MyFunc() 函式重解釋 func() 的例外 */
36 void MyFunc(int i)
37 {
38     try
39     {
40         func(i);
41     }
42     catch(int i)
43     {
44         switch(i)
45         {
46             case -1:
47                 throw "Invalid Parameter";   // 可以拋出更詳細的資料,如類物件,后續講解
48                 break;
49             case -2:
50                 throw "Runtime Exception";
51                 break;
52             case -3:
53                 throw "Timeout Exception";
54                 break;
55         }
56     }
57 }
58 
59 int main(int argc, char *argv[])
60 {
61     try
62     {
63         MyFunc(11);
64     }
65     catch(const char* cs)
66     {
67         cout << "Exception Info: " << cs << endl;
68     }
69     
70     return 0;
71 }
72 /**
73  * 運行結果:
74  * Exception Info: Timeout Exception
75  */
模擬 第三方庫例外代碼(改進版)

 

 3、自定義例外類的使用方式

  (1)例外的型別可以是自定義型別別;

  (2)對于型別別例外的匹配依舊是自上而下嚴格匹配;

  (3)賦值兼容性原則在例外匹配中依然適用;(注:在賦值兼容性中,子類是特殊的父類,父類可以捕獲子類的例外;同樣滿足例外型別嚴格匹配的原則)

    (4)在賦值兼容性原則中,一般將

    1)匹配子類例外的 catch 放在上部;

    2)匹配父類例外的 catch 放在下部;

  (5)在定義 catch 陳述句塊時,推薦使用 const 參考作為引數,提高程式的運行效率;

  1 #include <iostream>
  2 #include <string>
  3 
  4 using namespace std;
  5 
  6 class Base
  7 {
  8 };
  9 
 10 /* 定義例外類 */
 11 class Exception : public Base
 12 {
 13     int m_id;
 14     string m_desc;
 15 public:
 16     Exception(int id, string desc)
 17     {
 18         m_id = id;
 19         m_desc = desc;
 20     }
 21     
 22     int id() const
 23     {
 24         return m_id;
 25     }
 26     
 27     string description() const
 28     {
 29         return m_desc;
 30     }
 31 };
 32 
 33 /*
 34     假設: 當前的函式式第三方庫中的函式,因此,我們無法修改源代碼
 35     函式名: void func(int i)
 36     拋出例外的型別: int
 37                         -1 ==》 引數例外
 38                         -2 ==》 運行例外
 39                         -3 ==》 超時例外
 40 */
 41 
 42 void func(int i)
 43 {
 44     if( i < 0 )
 45     {
 46         throw -1;
 47     }
 48     
 49     if( i > 100 )
 50     {
 51         throw -2;
 52     }
 53     
 54     if( i == 11 )
 55     {
 56         throw -3;
 57     }
 58     
 59     cout << "Run func..." << endl;
 60 }
 61 
 62 /* 使用自定義的型別別來優化 */
 63 void MyFunc(int i)
 64 {
 65     try
 66     {
 67         func(i);
 68     }
 69     catch(int i)
 70     {
 71         switch(i)
 72         {
 73             case -1:
 74                 throw Exception(-1, "Invalid Parameter");  // 直接呼叫建構式生成例外物件;
 75                 break;
 76             case -2:
 77                 throw Exception(-2, "Runtime Exception");
 78                 break;
 79             case -3:
 80                 throw Exception(-3, "Timeout Exception");
 81                 break;
 82         }
 83     }
 84 }
 85 
 86 int main(int argc, char *argv[])
 87 {
 88     try
 89     {
 90         MyFunc(11);
 91     }
 92     catch(const Exception& e)  // 1 使用 const 參考型別作為引數  2 賦值兼容性原則(參考第4點)
 93     {
 94         cout << "Exception Info: " << endl;
 95         cout << "   ID: " << e.id() << endl;
 96         cout << "   Description: " << e.description() << endl;
 97     }
 98     catch(const Base& e) 
 99     {
100         cout << "catch(const Base& e)" << endl;
101     }
102     
103     return 0;
104 }
105 /**
106  * 運行結果:
107  * Exception Info:
108  * ID: -3
109  * Description: Timeout Exception
110  */
模擬 第三方庫例外代碼(完美版)

 

4、C++ 標準庫中的例外類

  (1)C++ 標準庫中提供了實用例外類族;

  (2)標準庫中的例外都是從 exception 類派生的;

  (3)exception 類有兩個主要的分支:

    1)logic_error

         2)runtime_error

     (4)標準庫中的例外類繼承圖:

    

 1 #include <iostream>
 2 #include <string>
 3 #include <stdexcept> 
 4 #include <sstream>
 5 
 6 using namespace std;
 7 
 8 /*
 9     __FILE__  __FUNCTION__  const char[]
10     __LINE__  int
11 */
12 
13 template
14 <typename T, int N>
15 class Array
16 {
17 private:
18     T arr[N];
19 public:
20     Array();
21     T& operator[] (int index);
22     void print() const;
23 };
24 
25 template
26 <typename T, int N>
27 Array<T, N>::Array()
28 {
29     for(int i = 0; i < N; i++)
30     {
31         arr[i] = 0;
32     }
33 }
34 
35 template
36 <typename T, int N>
37 T& Array<T, N>::operator[] (int index)
38 {
39     if( (0 <= index) && (index < N) )
40     {
41         return arr[index];
42     }
43     else
44     {
45         ostringstream oss;
46         
47         throw out_of_range(string(__FILE__) + ":" + static_cast<ostringstream&>(oss << __LINE__).str() + ":" + __FUNCTION__\
48 
49                         + "\t >> exception: the index of array is out of range");  
50     }
51 }
52 
53 template
54 <typename T, int N>
55 
56 void Array<T, N>::print() const
57 {
58     for(int i = 0; i < N; i++)
59     {
60         cout << arr[i] << " ";
61     }
62     cout << endl;
63 }
64 
65 int main(int argc, char *argv[])
66 {
67     try
68     {
69         Array<int, 5> arr;
70 
71         arr.print();
72         arr[-1] = 1;    // 例外測驗
73         arr.print();
74     }
75 
76     catch(const out_of_range& e)  // 1 使用 const 參考型別作為引數  2 賦值兼容性原則(參考第4點)
77     {
78         cout << e.what() << endl;
79     }
80 
81     catch(...)
82     {
83         cout << "other exception ... " << endl;
84     }
85 
86     return 0;
87 }
88 
89 /**
90  * 運行結果:
91  * 0 0 0 0 0
92  * test.cpp:47:operator[]     >> exception: the index of array is out of range
93  */
out_of_range例外類的使用

 

  1 // 模板檔案 Array.hpp 的優化
  2 #ifndef ARRAY_H
  3 #define ARRAY_H
  4 
  5 #include <stdexcept>  // 標準庫中的例外類頭檔案;
  6 
  7 using namespace std;A
  8 
  9 template
 10 < typename T, int N >
 11 class Array
 12 {
 13     T m_array[N];
 14 public:
 15     int length() const;
 16     bool set(int index, T value);
 17     bool get(int index, T& value);
 18     T& operator[] (int index);
 19     T operator[] (int index) const;
 20     virtual ~Array();
 21 };
 22 
 23 template
 24 < typename T, int N >
 25 int Array<T, N>::length() const
 26 {
 27     return N;
 28 }
 29 
 30 template
 31 < typename T, int N >
 32 bool Array<T, N>::set(int index, T value)
 33 {
 34     bool ret = (0 <= index) && (index < N);
 35     
 36     if( ret )
 37     {
 38         m_array[index] = value;
 39     }
 40     
 41     return ret;
 42 }
 43 
 44 template
 45 < typename T, int N >
 46 bool Array<T, N>::get(int index, T& value)
 47 {
 48     bool ret = (0 <= index) && (index < N);
 49     
 50     if( ret )
 51     {
 52         value =https://www.cnblogs.com/nbk-zyc/p/ m_array[index];
 53     }
 54     
 55     return ret;
 56 }
 57 
 58 template
 59 < typename T, int N >
 60 T& Array<T, N>::operator[] (int index)
 61 {
 62     if( (0 <= index) && (index < N) )
 63     {
 64         return m_array[index];  // 這里之前沒有驗證 index 是否合法,因為驗證了也沒辦法處理;
 65     }
 66     else
 67     {
 68         throw out_of_range("T& Array<T, N>::operator[] (int index)");
 69     }
 70 }
 71 
 72 template
 73 < typename T, int N >
 74 T Array<T, N>::operator[] (int index) const
 75 {
 76     if( (0 <= index) && (index < N) )
 77     {
 78         return m_array[index];  // 這里之前沒有驗證 index 是否合法,因為驗證了也沒辦法處理;
 79     }
 80     else
 81     {
 82         throw out_of_range("T Array<T, N>::operator[] (int index) const");
 83     }
 84 }
 85 
 86 template
 87 < typename T, int N >
 88 Array<T, N>::~Array()
 89 {
 90 
 91 }
 92 
 93 #endif
 94 
 95 //------------------------------------------------------------------
 96 
 97 // 模板檔案 HeapArray.hpp 的優化
 98 
 99 #ifndef HEAPARRAY_H
100 #define HEAPARRAY_H
101 
102 #include <stdexcept>  // 添加標準頭檔案;
103 
104 using namespace std;
105 
106 template
107 < typename T >
108 class HeapArray
109 {
110 private:
111     int m_length;
112     T* m_pointer;
113     
114     HeapArray(int len);
115     HeapArray(const HeapArray<T>& obj);
116     bool construct();
117 public:
118     static HeapArray<T>* NewInstance(int length); 
119     int length() const;
120     bool get(int index, T& value);
121     bool set(int index ,T value);
122     T& operator [] (int index);
123     T operator [] (int index) const;
124     HeapArray<T>& self();
125     const HeapArray<T>& self() const;  // 要考慮成員函式有沒有必要成為 const 函式,const 函式主要是給 cosnt 物件呼叫;
126     ~HeapArray();
127 };
128 
129 template
130 < typename T >
131 HeapArray<T>::HeapArray(int len)
132 {
133     m_length = len;
134 }
135 
136 template
137 < typename T >
138 bool HeapArray<T>::construct()
139 {   
140     m_pointer = new T[m_length];
141     
142     return m_pointer != NULL;
143 }
144 
145 template
146 < typename T >
147 HeapArray<T>* HeapArray<T>::NewInstance(int length) 
148 {
149     HeapArray<T>* ret = new HeapArray<T>(length);
150     
151     if( !(ret && ret->construct()) ) 
152     {
153         delete ret;
154         ret = 0;
155     }
156         
157     return ret;
158 }
159 
160 template
161 < typename T >
162 int HeapArray<T>::length() const
163 {
164     return m_length;
165 }
166 
167 template
168 < typename T >
169 bool HeapArray<T>::get(int index, T& value)
170 {
171     bool ret = (0 <= index) && (index < length());
172     
173     if( ret )
174     {
175         value =https://www.cnblogs.com/nbk-zyc/p/ m_pointer[index];
176     }
177     
178     return ret;
179 }
180 
181 template
182 < typename T >
183 bool HeapArray<T>::set(int index, T value)
184 {
185     bool ret = (0 <= index) && (index < length());
186     
187     if( ret )
188     {
189         m_pointer[index] = value;
190     }
191     
192     return ret;
193 }
194 
195 template
196 < typename T >
197 T& HeapArray<T>::operator [] (int index)
198 {
199     if( (0 <= index) && (index < length()) )
200     {
201         return m_pointer[index];  // 優化這里,越界拋例外;
202     }
203     else
204     {
205         throw out_of_range("T& HeapArray<T>::operator [] (int index)");
206     }
207 }
208 
209 template
210 < typename T >
211 T HeapArray<T>::operator [] (int index) const
212 {
213     if( (0 <= index) && (index < length()) )
214     {
215         return m_pointer[index];  // 優化這里,越界拋例外;
216     }
217     else
218     {
219         throw out_of_range("T HeapArray<T>::operator [] (int index) const");
220     }
221 }
222 
223 template
224 < typename T >
225 HeapArray<T>& HeapArray<T>::self()
226 {
227     return *this;
228 }
229 
230 template
231 < typename T >
232 const HeapArray<T>& HeapArray<T>::self() const
233 {
234     return *this;
235 }
236 
237 template
238 < typename T >
239 HeapArray<T>::~HeapArray()
240 {
241     delete[]m_pointer;
242 }
243 
244 #endif
245 
246 //------------------------------------------------------------------
247 
248 // 測驗檔案 main.cpp 
249 
250 #include <iostream>
251 #include <string>
252 #include <memory>  //for auto_ptr
253 #include "Array.hpp"
254 #include "HeapArray.hpp"
255 
256 using namespace std;
257 
258 void TestArray()
259 {
260     Array<int, 5> a;
261     
262     for(int i=0; i<a.length(); i++)
263     {
264         a[i] = i;   
265     }
266     
267     for (int i=0; i<a.length(); i++)
268     {
269         cout << a[i] << ", ";
270     }
271     cout << endl;
272 }
273 
274 void TestHeapArray()
275 {
276     //使用智能指標,目的是自動釋放堆空間
277     auto_ptr< HeapArray<double> > pa(HeapArray<double>::NewInstance(5));
278     
279     if(pa.get() != NULL)
280     {
281         HeapArray<double>& array = pa->self();
282         
283         for(int i=0; i<array.length(); i++)
284         {
285             array[i] = i;
286         }
287         
288         for (int i=0; i<array.length(); i++)
289         {
290              cout << array[i] << ", ";
291         }
292         cout << endl;         
293     }         
294 }
295 
296 int main(int argc, char *argv[])
297 {
298     try
299     {
300         TestArray();
301 
302         cout << endl;     
303 
304         TestHeapArray();
305     }
306     catch(const out_of_range& e)
307     {
308         cout << "exception: " << e.what() << endl;
309     }
310     catch(...)
311     {
312         cout << "other exception ... " << endl;
313     }   
314 
315     return 0;
316 }
317 
318 /**
319  * 運新結果:
320  * 0, 1, 2, 3, 4, 
321  * ---------------------
322  * 0, 1, 2, 3, 4, 
323  * Run End...
324  */
325 
326 /**
327  * 堆疊空間陣列下標越界例外運行結果:
328  * exception: T& Array<T, N>::operator[] (int index)
329  * Run End...
330  */
331 
332 /**
333  * 堆空間陣列下標越界例外運行結果:
334  * 0, 1, 2, 3, 4, 
335  * ---------------------
336  * exception: T& HeapArray<T>::operator [] (int index)
337  * Run End...
338  */
標準庫中陣列下標越界例外案列

 

5、try..catch 另類寫法 和  函式例外宣告/定義 throw()

   try..catch 另類寫法(不建議使用)的特點:

  (1)try-catch用于分隔正常功能代碼與例外處理代碼

  (2)try-catch可以直接將函式實作分隔為2部分

  函式例外宣告/定義的特點:

  (1)函式宣告和定義時可以直接指定可能拋出的例外型別;

  (2)例外宣告成為函式的一部分,可以提高代碼可讀性;

  (3)函式例外宣告是一種與編譯器之間的契約;

  (4)函式宣告例外后就只能拋出宣告的例外;

    A、拋出其它例外將導致程式運行終止;

    B、可以直接通過例外宣告定義無例外函式;

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 // int func(int i, int j) throw()  // 無例外函式宣告
 7 
 8 int func(int i, int j) throw(int, char)  //例外宣告,表示該函式可能拋出int和char兩種型別的例外
 9 {
10     if ((0 < j) && (j < 10))
11     {
12         return (i + j);
13     } 
14     else
15     {
16         throw 'c'; // 只能拋出指定的例外型別(int、char),否則程式運行失敗
17     }
18 }
19 
20 //以下的寫法已經不被推薦  !!!
21 void test(int i) try   //正常代碼
22 {
23     cout << "func(i, i) = " << func(i, i) << endl;
24 }
25 catch (int j)   //例外代碼
26 {
27     cout << "Exception: " << j << endl;
28 }
29 catch (char j)   //例外代碼
30 {
31     cout << "Exception: " << j << endl;
32 }
33 
34 int main(int argc, char *argv[])
35 {
36     test(5); //正常
37 
38     test(10); //拋例外
39 
40     return 0;
41 }
42 /**
43  * 運行結果:
44  * func(i, i) = 10
45  * Exception: c
46  */
try..catch的另類寫法 + throw 宣告例外型別

  

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/52960.html

標籤:C++

上一篇:L1-004 計算攝氏溫度 (5分)

下一篇:L1-005 考試座位號 (15分)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more