Hello,
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!
-
Are you expecting some sort of exception to be thrown? If you are, can you catch it? If not, then I don't see the point of the try/finally.
There's also differing philosophies on exceptions. Personally, I think of them as being 'exceptional'-- like the power went out when your last file write took place, so your serialized file is shorter than you're expecting. I'm not sure what kind of exceptional situation can happen when you manipulate bits like this. If you walk off the end of the array, that's not exceptional, that just means you need to tighten your bounds checking.
Chris : A good point, here. The code is not ours; it belongs to a proprietary library that we work with.From mmr -
Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option.
-
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.
0 comments:
Post a Comment