Unlock, block and try at last

I am invoking code that uses the BitmapData class from .NET. I hit something where I cannot find the final answer on Googlespace.

Since it seems that LockBits and UnlockBits should always be called in pairs, I use this:

System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits( new System.Drawing.Rectangle(0, 0, tempImage.Width, tempImage.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, tempImage.PixelFormat); try { //use external library on the data }//Exception not handled here; throw to calling method finally { tempImage.UnlockBits(tempImageData); } 

(I recently played using the using statement, which is very useful in C #, which gave me an idea that I should do this.) The problem is that even the MS documentation ( http://msdn.microsoft.com/ en-us / library / system.drawing.bitmap.unlockbits.aspx ) does not see that it is suitable for using the try-finally template.

Is the attempt - finally, necessary or free?

Update: I can end up catching and re-throwing the exception, since I don't know what it might be and didn't catch them before.

Thanks!

+5
source share
3 answers

The try-finally pattern is correct. Since this is external code, you have no control over which exceptions were thrown, and the UnlockBits cleanup code should be executed regardless of the error that occurred.

+7
source

Even if you catch an exception, use finally means that you are not duplicating the UnlockBits call, which is a plus in my option.

+1
source

Do you expect some kind of exception? If so, can you catch him? If not, then I do not see the try / finally point.

There are also different philosophies with exceptions. Personally, I consider them "exceptional" - as if the power went out when your last file entry happened, so your serialized file is shorter than you expect. I am not sure what kind of exception can happen when you manipulate such bits. If you exit the end of the array, this is not exceptional, it just means you need to tighten the bounds check.

0
source

Source: https://habr.com/ru/post/970367/


All Articles