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

3

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

有什么想法吗?


6
你尝试过联系支持团队了吗? - 463035818_is_not_a_number
3
新分配在您操作之前会抛出异常。 - Galik
4
@tobi303,是的,他们说你有令人难以置信的幽默感。 - user5296719
2
请缩进你的代码。 - Jabberwocky
3
Galik是正确的(您可以使用catch(const std::exception& e) {...}或者const std::bad_alloc&来捕获该异常,如果只想非常严格地捕获它)。此外,在catch之后不应该调用delete[] arr;,如果new抛出异常,arr将具有垃圾值并导致程序崩溃。 - Tony Delroy
1个回答

7

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

您可以删除带有if和try的块,并尝试捕获由new操作符抛出的异常。或者使用std::nothrow

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

运算符用于分配内存


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接