bad_array_new_length in C++

bad_array_new_length: This is available in the file new. 

Type of the exceptions thrown by array new-expressions:

Case -1.If the array size is less than zero.

Case -2.If the array size is greater than an implementation-defined limit. 

Case - 3.If the number of elements in the initializer list exceeds the number of elements to initialize. 

Note: This class is derived from bad_alloc (which is itself derived from exception).

Approach

C++

#include <bits/stdc++.h>
using namespace std;
int main()
{

    try
    {
        int size = -10;
        int *arr = new int[size];
    }
    catch (std::bad_array_new_length &e)
    {
        std::cerr << "bad_array_new_length occured " << 
e.what() << '\n';
    }

    return 0;
}

Output: bad_array_new_length occured std::bad_array_new_length because the size of the array is less than zero (i.e  -10) So, it occurs into the Case -1.

No comments:

Post a Comment