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 {
public:
my_exception() {};
virtual const char* what() const throw() {
return "Memory Error: Can't allocate enough memory";
}
};
class can_throw_exception {
public:
can_throw_exception() {};
void throw_exception() {
int* p = new int[9999999999999999999999];
delete [] p;
}
};
int main() {
try {
can_throw_exception c;
c.throw_exception();
}
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 what()
function didn't been called. How to override correctly std::bad_alloc exception ?
Aucun commentaire:
Enregistrer un commentaire