Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 371
gene Avatar asked Dec 20 '22 05:12

gene


2 Answers

The using statement is just a syntactic shortcut for a try/finally block. So yes, the object inside the using will be disposed in the case of an exception being thrown. Put another way:

using(var foo = new Foo())
{
}

Essentially gets compiled into:

Foo foo;

try
{
    foo = new Foo();
}
finally
{
    foo.Dispose();
}
like image 101
Craig W. Avatar answered Jan 04 '23 23:01

Craig W.


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 {}
}
like image 44
Michael Sander Avatar answered Jan 05 '23 00:01

Michael Sander