Dangers of Exceptions and the using statement
A little while ago I wrote about the advantages of the using statement. It pretty much guarantees that the dispose method will get called, even if an exception occurs in the middle of your code. One expansion on this I recently discovered is that even if you have multiple nested using statements, and one of the dispose methods throws an exception, the other dispose methods will still get called.
However, there are a few rare occasions you need to watch out for, lest you trip up. Consider the following code:
class DisposableTestException : Exception { }
class InnerBlockException : Exception { }
class DisposableTest : IDisposable
{
public DisposableTest()
{
Console.WriteLine("DisposableTest Object Created");
}
public void Dispose()
{
Console.WriteLine("DisposableTest Object Disposed");
throw new DisposableTestException();
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (DisposableTest disposableObject = new DisposableTest())
{
Console.WriteLine("Inner Loop");
throw new InnerBlockException();
}
}
catch (DisposableTestException)
{
Console.WriteLine("DisposableTextException Caught");
}
catch (InnerBlockException)
{
Console.WriteLine("InnerBlockException Caught");
}
}
}
What will be displayed?
DisposableTest Object Created
Inner Loop
DisposableTest Object Disposed
DisposableTestException Caught
As you can hopefully see the InnerBlockException has disappeared. This shouldn't be too much of a problem if you are careful, but if you are trying to abuse Exceptions you could come unstuck.
