The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,781 other followers

Archive for September 22nd, 2011

C# Using Blocks can Swallow Exceptions | DigitallyCreated

Posted by jpluimers on 2011/09/22

I got to the SafeUsingBlock extension method because of a nice StackOverflow thread on exceptions swallowed in a using block.

Actually, you can broaden the case into a wider scope: in any language when you protect resources in a try finally block (essentially, a using will turn into an implicit try finally block), and both the core logic and the finally throw an exception, the exception from the core block is swallowed.

Simple C# example:

using System;
public class Example
{
    public void Main()
    {
        try
        {
                try
                {
                    throw new ApplicationException("logic block");
                }
                finally
                {
                    throw new ApplicationException("finally block");
                }
        }
        catch (Exception error)
        {
            Console.WriteLine(error.ToString());
        }
    }
}

Simple Delphi example:

program Example;
begin
  try
    try
      raise Exception.Create('logic block');
    finally
      raise Exception.Create('finally block');
    end;
  except
    on error: Exception do
    begin
      Write(error.ClassName, ' ', error.Message);
    end;
  end;
end.

Both examples will only write out the finally block exception message, not the logic block exception message.

This is a corner case (like the example from the MSDN documentation), from which the SafeUsingBlock protects you from by providing an AggregateException class.

In C#, it is a guideline to avoid throwing exceptions in the Dispose when implementing the disposable pattern.

This is good practice in any programming environment: when disposing objects, only throw exceptions in very critical situations when the containing process has been corrupted.

Practically this is very easy as the disposers are very thin and should not contain any business logic, so it is pretty easy to spot places where the program state really is corrupt.

An other alternative is for instance have a Close method that throws an exception, and a disposer not throwing.

–jeroen

via C# Using Blocks can Swallow Exceptions | DigitallyCreated.

Posted in .NET, C#, Delphi, Development, Software Development | 7 Comments »

 
%d bloggers like this: