views:

704

answers:

3

I am getting OutOfMemory Exception in my .net addin. The addin is using large number of managed and unmanaged objects. Is there a way to trap this exception?

Updated: I think any application can get an OutofMemory exception if it processess a large amount of data that needs to be processed and not freed periodically. Suppose I have a method that analyses some structures in memory. I give it 300 structures, it loads each of them in memory, analyses them and completes processing. In this operation the memory usage was X. Now if I give it 3000 structures to process, it is going to analyze those 3000 in memory and the memory usage will go to 10X.

Updated

This problem is only seen in Excel 2007 and not in Excel 2003 which I why I have asked a MSDN personnel to look into it.

+2  A: 

In .Net the OutOfMemoryException is throw by the runtime when it cannot allocate the requested memory for your application. As such there is very little actual work that can be done to handle such an exception.

Instead of catching it you should prevent it from happening in the first place. Ignoring the exception will not make the problem go away.

Brian Rasmussen
Accepted this as the answer because after investigating it further, the MSDN guys found out that Excel was going out of memory as the available GDI Objects are all used up by structures (images). The default available GDI object limit for a process is 10,000 (which can be increased to 65536 by tweaking the registry but it not recommended). I have now put a check on the number of GDI objects used by structures >> "Instead of catching it you should prevent it from happening"
A9S6
That is good to know. Thanks for the update.
Brian Rasmussen
A: 

If you get an OutOfMemoryException your program has died, ceased to exist, passed on, it is no more and has gone to meet its maker.

But seriously, it's not able to recover some of the memory it's run out of so you can't do anything.

Garry Shutler
A: 

It could be the garbage collector getting you. Try periodically forcing collection.

If that doesn't help, read this: http://www.simple-talk.com/dotnet/.net-framework/the-dangers-of-the-large-object-heap/

R Ubben