Search code examples
c#winformshttpwebrequesttry-catchusing-statement

Will the clean-up logic still get called if an exception is thrown from within a using statement?


I have some questions about using the using keyword. I have the following code:

try {
   using (System.Net.WebResponse response = httpWebRequest.GetResponse()) {
      throw new Exception("Example");
   }
} 

catch ( Exception ex ) { 
}

My question is, when the exception occurs will it close the connection? Or do I have to close the connection inside the catch?


Solution

  • Yes, it will close the connection.

    The entire point of a using is that it will dispose the object when you leave the scope of the using, even if it is through an exception.

    a using block is, under the hood, implemented using a try/finally block.

    This is easy enough to test experimentally as well:

    public class Foo : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("I was disposed!");
        }
    }
    
    private static void Main(string[] args)
    {
        try
        {
            using (var foo = new Foo())
                throw new Exception("I'm mean");
        }
        catch { }
     }
    

    And the output is:

    I was disposed!