C++内存分配异常处理

在内存分配失败的情况下,new会抛出bad_alloc的异常,而malloc会返回空指针

a. new异常处理
try 
{ 
	int* a = new int[8000000000];
	cout << "get memory" << endl; 
} 
catch(bad_alloc& ba) 
{
	cout << "catch the exception" << endl; 
}

b. malloc异常处理:
int* a = (int*)malloc(8000000000);
if(NULL == a)
{
	cout << "alloc memory failed" << endl;
}  

c. new也可以通过判断返回值处理异常
int* a = new(std::nothrow)int[8000000000];
if(NULL == a)
{
	cout << "alloc memory failed" << endl;
}  

你可能感兴趣的:(exception,null)