使用 new 发生失败时会抛出一个异常,在标准 C++ 中是抛出一个 bad_alloc 类型异常,如果程序中不能捕捉这个异常,那么程序将被终止。要使用这种类型的异常,必须包含 <new> 头文件。
下面程序演示使用 try/catch 来监控运算符 new 在内存分配失败时产生的异常:
[C++] 纯文本查看 复制代码 #include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
try {
p = new int[9999999999999];
}
catch (bad_alloc xa) {
cout << "Allocation failure.\n";
return 1;
}
delete [] p;
cout << "Allocation OK, has deleted the allocated memory.\n";
return 0;
}
编译时会发出警告,但仍然能生成可执行文件:g++ newexp.cc -o newexp
newexp.cc:11:15: warning: integer constant is too large for its type [enabled by default] 运行输出:
./newexp
Allocation failure. |