I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace.
Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using 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've recently been playing around with the using statement, which is very useful in C#, which gave me the idea that I should do this.) Trouble is, even MS's own documentation (http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx) doesn't see it fit to use the try-finally pattern.
Is try-finally necessary or gratuitous?
Update: I may end up catching and rethrowing the exception, since I don't know what it might be and wasn't catching them earlier.
Thanks!
The try-finally pattern is correct. Since this is external code, you have no control over what exceptions are thrown, and the UnlockBits cleanup code needs to be executed regardless of what error has occurred.
Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With