C++利用new_handler()函數處理異常
C++規定,new_handler要執行下述操作中的一種:
(1)使new有更多的內存使用,然後返回
(2)拋出一個bad_alloc異常或者其派生異常
(3)調用abort或者exit退出
下面舉例說明,程序通過VS2008編譯運行
#include <iostream>
#ifndef NUL
#define NUL '\0'
#endif
char* gPool = NULL;
void my_new_handler(void);//內存分配失敗時調用這個函數
int main(void)
{
std::set_new_handler(my_new_handler);
try
{
gPool = new char[100*1<<20];
printf("alloc 100M memory for gPool! %#x\n",gPool);
}
catch ( ...)//用catch捕獲異常
{
printf("gPool alloc memory failed!\n");
throw std::bad_alloc();
}
char* p = NULL;
for (int i = 0;i<20;++i)
{
p = new char [100*1<<20];
printf("alloc %dM memory for p!\n",(i+1)*100 );
}
printf("done...\n");
return NULL;
system("pause");
}
void my_new_handler(void)//用new_handler捕獲異常並處理
{
if (gPool != NULL)
{
printf("try to get memory....\n");//幫助系統獲得更多內存
delete [] gPool;
gPool = NULL;
return ;
}
else
{
printf("i can't help more...\n");
throw std::bad_alloc();
return ;
}
}