在本文中, 我自己来写一个异常类my_own_exception, 主要为了感知一下C++异常机制, 看代码:
#include <iostream>
using namespace std;
class my_own_exception
{
private:
char szMsg[1024];
public:
my_own_exception(const char *p)
{
memset(szMsg, 0, sizeof(szMsg));
strncpy(szMsg, p, sizeof(szMsg) - 1);
}
const char *what()
{
return szMsg;
}
};
int main()
{
try
{
int x = 1;
int y = 0;
if(0 == y)
{
throw my_own_exception("error!!!");
}
}
catch(my_own_exception &e)
{
cout << e.what() << endl;
}
return 0;
}
结果:error!!!
但在玩这代码的时候, 我发现了一个奇怪的问题:
#include <iostream>
using namespace std;
class my_own_exception
{
public:
~my_own_exception()
{
cout << "destructor" << endl;
}
};
int main()
{
try
{
throw my_own_exception();
}
catch(...)
{
}
return 0;
}
结果是:
destructor
destructor
再看程序:
#include <iostream>
using namespace std;
class my_own_exception
{
public:
~my_own_exception()
{
cout << this << endl;
cout << "destructor" << endl;
}
};
int main()
{
try
{
throw my_own_exception();
}
catch(...)
{
}
return 0;
}
结果是:
0013FF68
destructor
0013FF6C
destructor
继续看程序:
#include <iostream>
using namespace std;
class my_own_exception
{
public:
virtual ~my_own_exception()
{
cout << this << endl;
cout << "destructor" << endl;
}
};
int main()
{
try
{
throw my_own_exception();
}
catch(...)
{
}
return 0;
}
结果是:
0013FF6C
destructor
2. 3 4程序的具体原因, 我还没有太弄懂, 等以后弄懂了, 再回来完善本文。 有清楚的朋友, 也请不吝赐教。