std::bad_array_new_length class in C++ with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

std::bad_array_new_length

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

std::bad_array_new_length

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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.