#include<iostream>
#include<exception>
#include<tchar.h>
#include<time.h>
//内存异常,通过异常申述来让上游模块得知下游模块的异常
void NewAllocation(int iSize) throw(std::bad_alloc(), int)
{
try
{
int* p = new int[99999999];
throw std::bad_alloc();
p[1000000] = 1000;
_tprintf(_T("%d\n"),p[1000000]);
delete p;
p = NULL;
}
catch( std::bad_alloc)
{
_tprintf(_T("Error: NewAllocation...\n"));
srand(time(0));
int K = rand()%2;
if( 0 == K)
throw std::bad_alloc();
else
throw 2;
}
}
void TestAllocation()
{
_tprintf(_T("start TestAllocation...\n"));
try
{
NewAllocation(999999999);
}
catch( std::bad_alloc)
{
_tprintf(_T("Test: std::bad_alloc: Bad Allocation...\n"));
}
catch( int )
{
_tprintf(_T("Test: int Error: Bad Allocation...\n"));
}
_tprintf(_T("end of TestAllocation...\n"));
}
class ERROR
{
public:
virtual const TCHAR* what(){ return _T("ERROR"); }
};
class ERROR_A: public ERROR
{
public:
virtual const TCHAR* what(){ return _T("ERROR_A"); }
};
class ERROR_B: public ERROR
{
public:
virtual const TCHAR* what(){ return _T("ERROR_B"); }
};
void AError() throw (ERROR_A())
{
throw ERROR_A();
}
void BError() throw (ERROR_B())
{
throw ERROR_B();
}
//测试异常类的多态情况
void TestVirtual()
{
try
{
BError();
}
catch( ERROR& e)
{
_tprintf(_T("%s...\n"),e.what());
}
}
//测试非一脉相传的类dynamic_cast<>能否进行转换
//测试typeid是否只能配对类型
void TestCase()
{
try
{
ERROR_A* pa = new ERROR_A();
ERROR* pbase = pa;
ERROR_A *paa = dynamic_cast<ERROR_A *>(pbase);
if( NULL == paa)
throw 3;
//ERROR_B c;
//if( typeid(paa) == typeid(&c))
//{
// throw 3;
//}
//ERROR_B *pd1 = static_cast<ERROR_B *>(pa); //compile error
ERROR_B *pd2 = dynamic_cast<ERROR_B *>(pa); //pd2 is NULL
if( NULL == pd2)
throw std::bad_cast();
delete pa;
}
catch( std::bad_cast)
{
_tprintf(_T("failed in bad_cast...\n"));
}
catch( int )
{
_tprintf(_T("failed in int...\n"));
}
}
void main()
{
TestAllocation();
TestVirtual();
TestCase();
system("pause");
}