c++異常3

來源:互聯網
上載者:User

標籤:try catch 異常

#include <iostream>                                                                                                                    #include <iostream>using namespace std;class FileError{};class MemoryError{};void foo(void)throw(MemoryError,FileError,int,double);int main(void){    try{        foo();    }    catch(FileError& ex){        cout << "file error!" << endl;        return -1;    }    catch(MemoryError& ex){        cout << "memory error!" << endl;        return -1;    }    catch(int ex&){//int類型只能捕捉double,同樣double只能捕捉double.        cout << ex << endl;    }    catch(...){//這裡會捕捉所有異常列表的異常對象        cout << "other error!" << endl;        return -1;    }    return 0;}void foo(void)throw(FileError,MemoryError,int,double){//與函式宣告一樣,不多不少.    throw -1;    //throw FileError();}

異常說明:

1)可以在函數原型中增加異常說明,說明該函數所有可能拋出的異常類型.

 返回類類型 函數名(形參表)throw(對象1,對象2,...);(這裡對象可以為基本類型)

對象1,對象2...被稱為異常說明表

2)函數的異常說明是一種承諾,表示函數所拋出的異常不會超出異常說明表,如果超出,將無法被捕獲

即使catch中接受對象的類型也無法被捕獲,最終會被系統捕獲,終止程式.

3)throw;表示可以拋出任何異常,thow();表示不會拋出異常

4)如果函數申明和定義分開,如果聲明時有異常說明,則定義時也要有異常說明,異常說明表要一模一樣,

當然,異常說明表中異常對象的位置可以隨意.

5)如果基類中的虛函數帶有異常說明,那麼該函數在子類中的覆蓋版本不能在異常說明表中拋出的異常對象不能比基類多(屬於內含項目關聯性)

6)如果建構函式中拋出異常,則對象將不會調用解構函式(怎麼都不會調用),這時需要手動銷毀在異常之前

7)不允許在解構函式中拋出異常,如果你在析構中拋異常,這個類一旦執行個體化,就報錯.
所有動態分配的資源.

#include <iostream>using namespace std;class A{    public:        A():m_p(new int(5)){            cout << "A:A()" << endl;            delete m_p;            throw -1;//解構函式不會調用,拋出異常前,手動釋放動態分配的記憶體        }        ~A(){            cout << "haha" << endl;            delete m_p;        }                                                                                                                                  private:        int* m_p;};int main(void){    A a;//這樣就直接報錯.    return 0;}


本文出自 “12208412” 部落格,請務必保留此出處http://12218412.blog.51cto.com/12208412/1869629

c++異常3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.