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;
}