我正在学习C++中的异常处理,以下是我尝试在动态分配内存中应用它的方法:
#include <iostream>
using namespace std;
int main()
{
const char * message[] = {"Dynamic memory allocation failed! "};
enum Error{
MEMORY
};
int * arr, length;
cout << "Enter length of array: " << endl;
cin >> length;
try{
arr = new int[length];
if(!arr){
throw MEMORY;
}
}
catch(Error e){
cout << "Error!" << message[e];
}
delete [] arr;
}
它没有按照预期工作。如果我输入一些很大的长度值,而不是显示消息“动态内存分配失败!”(不带引号),我得到:
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
Process returned 3 (0x3) execution time : 3.835 s Press any key to continue.
有什么想法吗?
catch(const std::exception& e) {...}
或者const std::bad_alloc&
来捕获该异常,如果只想非常严格地捕获它)。此外,在catch
之后不应该调用delete[] arr;
,如果new
抛出异常,arr
将具有垃圾值并导致程序崩溃。 - Tony Delroy