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?
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();
}
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 {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With