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

时间:2015-09-03 12:17:55

标签: c++ exception-handling dynamic-memory-allocation

我在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;
}

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

  

在抛出&#39; std :: bad_alloc&#39;的实例后终止调用     what():std :: bad_alloc

     

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

     

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

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

Operator new本身会抛出错误。并且它的错误不是你指定的类型错误,所以如果内存不能被分配,那么你的if语句将永远不会被执行,因为异常将被抛出。

您可以使用if删除块并尝试捕获由new运算符抛出的异常。或者使用std::nothrow

 arr=new (std::nothrow)[length];

运算符分配内存