C++ Question

C++: how to override std::bad_alloc exception on my own class?

I'm trying to override std::bad_alloc in my own exception class like in the code given below

#include <iostream>
#include <exception>

class my_exception: public std::bad_alloc {
my_exception() {};
virtual const char* what() const throw() {
return "Memory Error: Can't allocate enough memory";

class can_throw_exception {
can_throw_exception() {};
void throw_exception() {
int* p = new int[9999999999999999999999];
delete [] p;

int main() {
try {
can_throw_exception c;
catch(const my_exception& error) {
std::cout << error.what() << std::endl;
return 0;

But when I run this code, I get this message

terminate called after throwing an instance of 'std::bad_alloc'

what(): std::bad_alloc Aborted (core dumped)

Which means that my version of
function didn't been called.
How to override correctly std::bad_alloc exception ?

Answer Source

I think you are missing where the exception is actually coming from.
When you allocate some memory chunk using new and there is not enough memory to succeed, the new operator throws an exception std::bad_alloc.

You can derive your own class from std::bad_alloc, however, this way you don't force the new operator to throw your exception. It will still throw the std::bad_alloc.

What you can do is overriding the new operator where you can throw your exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download