Will the disposable resource be remote if try / catch is used inside a "using" statement?
I work with SqlConnection
and SqlCommand
.
I need to catch the exception, if for example there is SqlException
.
I am using the suggestion using
and pasting try/catch block
inside 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 mine SqlConnection
and get SqlCommand
deleted in case of an exception and is a good approach to handle it, or should I just just use the old fashion method using a block try/catch/finally
?
source to share
In your case, the exception gets caught right inside the use, and dispose is executed when you leave the block in use.
But even if you put the using block outside try catch
and an exception is thrown, dispose is 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 {}
}
source to share
The operator using
is just a syntactic shortcut to the try
/ block finally
. So yes, the object inside using
will be removed in case of an exception thrown. In other words:
using(var foo = new Foo())
{
}
Essentially compiles to:
Foo foo;
try
{
foo = new Foo();
}
finally
{
foo.Dispose();
}
source to share