Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch out of memory exception in c++?

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 } 
like image 772
in His Steps Avatar asked Oct 13 '11 03:10

in His Steps


People also ask

Can you catch out of memory exception?

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.

How do I stop out of memory exception?

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.

What is out of memory exception?

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.


1 Answers

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.

like image 72
Mark Ransom Avatar answered Oct 10 '22 23:10

Mark Ransom