建構函式異常測試

來源:互聯網
上載者:User

http://www.cplusplus.com/doc/tutorial/

 

#include <iostream>
#include <exception>

using namespace std;

class MyTest_Base
{
public:
MyTest_Base (string name = "") : m_name(name)
{
cout << "構造一個MyTest_Base類型的對象,對象名為:"<<m_name << endl;
}

virtual ~ MyTest_Base ()
{
cout << "銷毀一個MyTest_Base類型的對象,對象名為:"<<m_name << endl;
}

void Func() //throw()
{
throw ("故意拋出一個異常,測試!");
}
void Other() {}

protected:
string m_name;
};

class MyTest_Parts
{
public:
MyTest_Parts ()
{
cout << "構造一個MyTest_Parts類型的對象" << endl;
}

virtual ~ MyTest_Parts ()
{
cout << "銷毀一個MyTest_Parts類型的對象"<< endl;
}
};

class MyTest_Derive : public MyTest_Base
{
public:
MyTest_Derive (string name = "") : MyTest_Base(name), m_component()
{
//throw ("在MyTest_Derive對象的建構函式中拋出了一個異常!");

cout << "構造一個MyTest_Derive類型的對象,對象名為:"<<m_name << endl;
}

virtual ~ MyTest_Derive ()
{
cout << "銷毀一個MyTest_Derive類型的對象,對象名為:"<<m_name << endl;
}

protected:
MyTest_Parts m_component;
};

int main()
{
try
{
// 物件建構時將會拋出異常
MyTest_Derive obj1("obj1");

obj1.Func();
obj1.Other();
}
catch(const char*s)
{
cout << s << endl;
}
catch(...)
{
cout << "unknow exception"<< endl;
}
return 0;
}

聯繫我們

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