Search code examples
c#language-featuresusingusing-statement

Why doesn't 'using' have a catch block?


I understand the point of "using" is to guarantee that the Dispose method of the object will be called. But how should an exception within a "using" statement be handled? If there is an exception, I need to wrap my "using" statement in a try catch. For example:


Lets say there is an exception created in the creation of the object inside the using parameter

 try
 {
    // Exception in using parameter
    using (SqlConnection connection = new SqlConnection("LippertTheLeopard"))
    {
       connection.Open();
    }
 }
 catch (Exception ex)
 {

 }

Or an Exception within the using scope

 using (SqlConnection connection = new SqlConnection())
 {
    try
    {
       connection.Open();
    }
    catch (Exception ex)
    {

    }
 }

It seems like if I already need to handle an exception with a try catch, that maybe I should just handle the disposing of the object as well. In this case the "using" statement doesn't seem to help me out at all. How do I properly handle an exception with "using" statement? Is there a better approach to this that I'm missing?

 SqlConnection connection2 = null;
 try
 {
    connection2 = new SqlConnection("z");
    connection2.Open();
 }
 catch (Exception ex)
 {

 }
 finally
 {
    IDisposable disp = connection2 as IDisposable;
    if (disp != null)
    {
       disp.Dispose();
    }
 }

Could the "using" keyword syntax be a little more sugary...
It sure would be nice to have this:

 using (SqlConnection connection = new SqlConnection())
 {
    connection.Open();
 }
 catch(Exception ex)
 {
   // What went wrong? Well at least connection is Disposed
 }

Solution

  • I've had places where this would be useful. But more often, when I want to do this it turns out that the problem is in my design; I'm trying to handle the exception in the wrong place.

    Instead, I need to allow it to go up to the next level — handle it in the function that called this code, rather than right there.