System.Drawing Out of Memory Exception

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.

Leave a Comment