Search code examples
c#winforms.net-3.5exceptionusing-statement

C# "using" statement and try/catch


Ive been doing some research today on when an how to use the "using" statement to dispose of my sql objects. However I'm still confused about when and how to catch unforseen errors. I have a simple method here and would appreciate any input on wheter its correct or I'm doing something wrong?

private BindingList<My_Object> Search(int ID)
{
   string strSelectStatement = 
     "SELECT 'coloumns' " +
     "FROM 'table' " +
     "WHERE ID = @ID;";

     DataTable dt = new DataTable();
     try
     {
        using (SqlConnection sqlConn = new SqlConnection(m_SQLConnectionString))
        {
          using (SqlCommand cmd = new SqlCommand(strSelectStatement, sqlConn))
          {
            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
            using (SqlDataAdapter adpt = new SqlDataAdapter(cmd))
            {
               adpt.Fill(dt);
            }
          }
        }

        My_Object myObject;
        BindingList<My_Object> myObjectList = new BindingList<My_Object>();

        foreach (DataRow row in dt.Rows)
        {
          myObject = new My_Object();
          //Fill/set myObject properties and add to myObject list
        }

        return myObjectList;
     }
     catch (Exception)
     {
        //throw the the exception with its stack trace up to the main call
        throw;
     }
}

So what my catch here would do is catch an error if anything went wrong when running adapter.Fill, or while building myObject/list for example.

Thanks


Solution

  • In C# . The using statement defines the scope of an item to be disposed. This can be called for any object which implements the IDisposable interface.

    http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

    So if you had to not use using blocks you would call the dispose method on the class to release/clean up resources created by the object.

    When calling a class that implements the IDisposable interface, the try/finally pattern make sure that unmanaged resources are disposed of even if an exception interrupts your application.

    If an exception is thrown in the case of a using statement the dispose will still be called. You can also stack using statements

    using (SqlConnection sqlConn = new SqlConnection(m_SQLConnectionString))
    using (SqlCommand cmd = new SqlCommand(strSelectStatement, sqlConn))
              {
                cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
                using (SqlDataAdapter adpt = new SqlDataAdapter(cmd))
                {
                   adpt.Fill(dt);
                }
              }
    

    with regards to exception handling. It is not wise to catch all exceptions try to catch the specific exceptions thrown by the class or method. You can view exception details on msdn so SQLConnection : http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx

    InvalidOperationException
    Cannot open a connection without specifying a data source or server.

    or

    The connection is already open.

    SqlException
    A connection-level error occurred while opening the connection. If the Number property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the ChangePassword method for more information.

    So these are the exceptions you should cater for. Hope that helps!