What is the std::bad_alloc exception in C++?

Exceptions in C++ are run-time anomalies or abnormal conditions that a program encounters during its execution. C++ provides the following specialized keywords for exception handling:

try: represents a block of code that can throw an exception.

catch: represents a block of code that is executed when a particular exception is thrown.

Definition

std::bad_alloc is a type of exception that occurs when the new operator fails to allocate the requested space. This type of exception is thrown by the standard definitions of ​operator new (declaring a variable) and operator new[] (declaring an array) when they fail to allocate the requested storage space.

svg viewer

Code

The following code displays the error message shown when std::bad_alloc is thrown.

#include <iostream>
#include <new>
// Driver code
int main () {
try
{
int * myarray = new int[1000000000000];
}
catch (std::bad_alloc & exception)
{
std::cerr << "bad_alloc detected: " << exception.what();
}
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved