简体   繁体   中英

C++ Exception handling and dynamic allocation of memory

I'm learning exception handling in C++, here is how I tried to apply it on dynamic allocation memory:

#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;
}

It doesn't work as it should, If I enter some huge number for length, instead of showing message "Dynamic memory allocation failed! " (without quotes) I got:

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.

Any idea?

Operator new itself throws an error. And it's error is not of type Error you specified, so if memory won't be able to be allocated, then your if statement will never be executed, because exception will already be thrown.

You can delete block with if and try to catch exception, that is thrown by new operator. Alternatively use std::nothrow

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

operator to allocate memory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM