Prerequisite : Exceptions in C++
Standard C++ contains several built-in exception classes. The most commonly used is bad_alloc, which is thrown if an error occurs when attempting to allocate memory with new.
This class is derived from exception.
To make use of bad_alloc, one should set up the appropriate try and catch blocks. Here’s a short example, that shows how it’s used :
C++
// CPP code for bad_alloc #include <iostream> #include <new> // Driver code int main () { try { int* gfg_array = new int[100000000]; } catch (std::bad_alloc & ba) { std::cerr << "bad_alloc caught: " << ba.what(); } return 0; } |
RunTime error :
bad_alloc caught: std::bad_alloc
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Custom Jumble Word Game
- Comparator Class in C++ with Examples
- Complete Guide to Install C++17 in Windows
- Features of C++
- Draw a triangle in C++ graphics
- Implementation of lower_bound() and upper_bound() in List of Pairs in C++
- How to Setup VSCode with C, C++ and Python for Competitive Programming
- Java System.exit(0) vs C++ return 0
- Features of C++17 with Examples
- Life cycle of Objects in C++ with Example
- Difference between virtual function and inline function in C++
- Difference between Turbo C++ and Dev C++
- Ellipsis in C++ with Examples
- Difference between Static and Dynamic Memory Allocation in C
- Const vs Regular iterators in C++ with examples
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.

