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

C++ Exception handling and dynamic allocation of memory

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

它没有正常工作,如果我输入了一个很大的长度数字,而不是显示消息 "Dynamic memory allocation failed! "(不带引号),我得到:

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.

有什么想法吗?

Operator new 本身抛出一个错误。而且它的错误不是你指定的错误类型,所以如果无法分配内存,那么你的 if 语句将永远不会执行,因为已经抛出了异常。

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

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

运算符分配内存