Skip to content
Related Articles

Related Articles

std::bad_array_new_length class in C++ with Examples
  • Last Updated : 28 May, 2020

Standard C++ contains several built-in exception classes, std::bad_array_new_length is one of them.It is an exception on bad array length and thrown if the size of array is less than zero and if the array size is greater than the limit. Below is the syntax for the same:

Header File:

<new>

Syntax:

class bad_array_new_length;

Return: The std::bad_array_new returns a null terminated character that is used to identify the exception.

Note: To make use of std::bad_array_new, one should set up the appropriate try and catch blocks.



Below are the Programs to understand the implementation of std::bad_array_new in a better way:

Program 1:




// C++ code for std::bad_array_new_length
#include <bits/stdc++.h>
  
using namespace std;
  
// main method
int main()
{
    int a = -1;
    int b = 1;
    int c = INT_MAX;
  
    // try block
    try {
        new int[a];
        new int[b]{
            1,
            2,
            3,
            4
        };
        new int[50000000];
    }
  
    // catch block to handle the errors
    catch (const bad_array_new_length& gfg) {
        cout << gfg.what() << endl;
    }
  
    return 0;
}
Output:
std::bad_array_new_length

Program 2:




// C++ code for std::bad_array_new_length
#include <bits/stdc++.h>
  
using namespace std;
  
// main method
int main()
{
    int a = -1;
    int b = 1;
    int c = INT_MAX;
  
    // try block
    try {
        new int[a];
        new int[b]{
            11,
            25,
            56,
            27
        };
        new int[1000000];
    }
  
    // catch block to handle the errors
    catch (const bad_array_new_length& gfg) {
        cout << gfg.what() << endl;
    }
    return 0;
}
Output:
std::bad_array_new_length

Reference: http://www.cplusplus.com/reference/new/bad_array_new_length/

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :