小编use*_*719的帖子

C++异常处理和内存动态分配

我正在学习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;
}
Run Code Online (Sandbox Code Playgroud)

它不能正常工作,如果我输入一些巨大的长度,而不是显示消息"动态内存分配失败!"(没有引号)我得到:

抛出'std :: bad_alloc'的实例后调用terminate():std :: bad_alloc

此应用程序已请求Runtime以不寻常的方式终止它.有关更多信息,请联系应用程序的支持团队.

进程返回3(0x3)执行时间:3.835 s按任意键继续.

任何的想法?

c++ exception-handling dynamic-memory-allocation

3
推荐指数
1
解决办法
1638
查看次数