I have a class where I allocate some memory. For Example:
class image {
public:
image(){
pixelvalue = 0;
}
void formatandcopy() {
pixelvalue = new int [10000*50000];
if(pixelvalue)
qDebug()<<"allocation successful";
else
qDebug()<<"allocation failed";
}
private:
int *pixelvalue;
};
When I call formatandcopy() the program throws this:
Qt has caught an exception thrown from an event handler. Throwing
exceptions from an event handler is not supported in Qt. You must
reimplement QApplication::notify() and catch all exceptions there.
Anyone know how I can prevent this and let the user know it’s simply out of memory? When I run this it doesn’t even show allocation failed. The above error is thrown before the qDebug() is called. The program runs fine if the amount of memory allocated is decreased. I thought this was strange since this error is thrown when using the new operator and not a qt function. Furthermore my machine has plenty of memory left. I assume this is a result of qt limiting it’s program to a certain heap space. Lastly, if I can fix this by indeed reimplementing the notify function then can anyone point me in the right direction to do this?
You should be able to catch std::bad_alloc to handle the exception within that function. The exception is part of standard C++.
If it gets beyond that scope (into the Qt event handling) then you will have to implement
QApplication::notifyas they specify.As a word of warning, bad allocations usually are not recoverable. The exception is when you know you are allocating a very large amount (perhaps based on user input) when you typically will not be using a very memory hungry application.
EDIT:
To clarify, if the design of your application allows you to run out of memory, then it is unlikely that anything will change if you catch bad_allocs and ignore them. The program is dead, you are only going to be able to display an error message about what happened. That is also tricky, because you cannot allocate any memory to create the message box!
The counter example is a scenario like asking the user for a file and reading it all into memory. Eventually they will try and give you a file that they don’t have the memory for and you can safely tell them to try another file. These sorts of problems are usually isolated in an application and well worth guarding against.