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