operator new's behaviour is defined as either returning valid memory or throwing a bad_alloc. There's no other possibility. It may not return null. It may not throw anything else.
But then is the output of my compiler wrong if the following program prints "Other error"?
Code:
#include <iostream>
#include <stdexcept>
class A
{
public:
A() { throw 1; }
};
int main()
{
try {
A* a = new A;
}
catch (std::bad_alloc&) {
std::cout << "Allocation error\n";
}
catch (int) {
std::cout << "Other error\n";
}
}
On one hand it is good to know that the problem was not allocating the memory but an exception was thrown from the constructor of the object. On the other hand it would mean that simply catching bad_alloc is not sufficient in all cases.