C++異常Exception

來源:互聯網
上載者:User

C++中的異常類只能捕獲普通異常,無法捕獲記憶體異常,除數為零等錯誤。

而後期語言,如java、C#能捕獲所有錯誤,包括記憶體異常等。

以下為C++的簡單異常處理類:

通過繼承實現異常處理
1、定義異常基類
2、定義具體異常類,繼承基類
3、給具體異常類異常資訊賦值

 1 /*通過繼承實現異常處理 2 1、定義異常基類 3 2、定義具體異常類,繼承基類 4 3、給具體異常類異常資訊賦值 5  */ 6 class Exception 7 { 8 public: 9     Exception()10     {11     }12     string ErrorMsg;13     string ErrorCode;14 };15 16 class Exception1:public Exception17 {18 public:19     Exception1()20     {21         this->ErrorMsg = "Msg1";22         this->ErrorCode = 1;23     }24 };25 26 class Exception2:public Exception27 {28 public:29     Exception2()30     {31         this->ErrorMsg = "Msg2";32         this->ErrorCode = 2;33     }34 };35 36 void test_exception()37 {38     int i = 0;39     //throw Exception1();40     throw Exception2();41     /*42     throw new Exception1();43     throw new Exception2();44     */45     return;46 }47 48 int main()49 {50     try51     {52         test_exception();53     }/*54     catch(Exception* ex)55     {56         cout<<ex->ErrorMsg<<endl;57     }*/58     59     catch(Exception ex)60     {61         cout<<ex.ErrorMsg<<endl;62     }63 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.