System.Drawing Out of Memory Exception

ScruffyDuck picture ScruffyDuck · Jun 28, 2011 · Viewed 16.4k times · Source

My application graphics engine throws these exceptions. They are all consumed by an empty catch block. In the early days I found one that was not trapped (associated with pen widening as I recall). I surrounded it with try and an empty catch block. It seems that these exceptions have no effect on the drawing produced. I have done some reading on this without really understanding or getting to the bottom of it.

So to my questions:

  1. Why would these be thrown if they can be consumed safely? and
  2. Is it safe to ignore them? I worry that each one is having some hidden effect. I have memory leaks which I have never found for example.

Answer

Joe White picture Joe White · Jun 28, 2011

I've seen System.Drawing throw OutOfMemoryExceptions even when it's not out of memory. Some GDI+ function is apparently just returning a stupid error code.

IIRC, you will get an OutOfMemoryException if you try to use a LinearGradientBrush to fill a rectangle whose width or height is zero. There may be other conditions too, but this is the main one we ran into.

In that case, there's no need for a try/catch. Just add an if statement to your drawing code, and don't fill the rectangle if the width or height is zero.

Update: According to the comments on this answer, it can also occur if you try to load a corrupted image file. For that, you would have no choice but to do try/catch.

You're probably safe catching OutOfMemoryExceptions from GDI+, but keep the try blocks as small as possible. Consider logging the exceptions, so you can analyze the logs and add defensive code where possible. You don't want to mask a real OutOfMemoryException, but you don't want a stupid GDI+ error code to crash your app either.