Search code examples
c#.nettry-catchidisposablesqlconnection

Will be Disposable resource disposed if try/catch is used inside "using" statement?


I'm working with SqlConnection and SqlCommand.

I have to catch an exception if, for example, there is any SqlException.

I'm using using clause and embed try/catch block inside of it. Here is the code:

public static void LogError(string error, string message)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connStringWeb"]))
    using (SqlCommand cmd = new SqlCommand("INSERT INTO errorLogTable (errorTime, errorType, error) VALUES(@errorTime, @errorText, @errorMsg)"))
    {
        cmd.CommandTimeout = 300;
        cmd.Connection = conn;
        cmd.Prepare();
        cmd.Parameters.AddWithValue("@errorTime", DateTime.Now);
        cmd.Parameters.AddWithValue("@errorText", error);
        cmd.Parameters.AddWithValue("@errorMsg", message);

        try
        {
           conn.Open();
           int i = cmd.ExecuteNonQuery();
        }
        catch { }
        }
   }
}

My question is, will my SqlConnection and SqlCommand be disposed in case of exception and is that a good approach to handle it or I should just simply use old fashion approach using try/catch/finally block?


Solution

  • In your case the exception is catched right inside the using and the dispose is executed when you leave the using block.

    But even if you put the using block outside the try catch and an exception is thrown, the dispose will be called.

    public static void LogError(string error, string message)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connStringWeb"]))
                using (SqlCommand cmd = new SqlCommand("INSERT INTO errorLogTable (errorTime, errorType, error) VALUES(@errorTime, @errorText, @errorMsg)"))
                {
                    cmd.CommandTimeout = 300;
                    cmd.Connection = conn;
                    cmd.Prepare();
                    cmd.Parameters.AddWithValue("@errorTime", DateTime.Now);
                    cmd.Parameters.AddWithValue("@errorText", error);
                    cmd.Parameters.AddWithValue("@errorMsg", message);
    
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                }
        }
        catch {}
    }