can anyone please tell me how to catch out of memory exception?
for ex.
try { while(true) { int i = new int; } } catch( ? <--- what should be put here?) { //exception handling }
and also this,
queue<int> q; try { while(true) { q.push(10); } } catch( ? <---- what should be put here?) { //error handling }
It is possible to catch an OutOfMemoryError (It's an Error , not an Exception ), but you should be aware, that there is no way to get a defined behaviour. You may even get another OutOfMemoryError while trying to catch it. So the better way is to create/use memory aware Caches.
Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory. Then you can calculate the length of your queue based on estimate of one object memory capacity. Another way would be to check for memory size in each worker thread.
OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.
Catch std::bad_alloc
.
You will also need a strategy for handling the errors, since many of the things you'd like to do will require memory (even if it's only to display an error to the user before shutting down). One strategy is to allocate a block of memory at startup, and delete
it in the exception handler before attempting to use more memory, so that there is some available to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With