如果在语句中使用 try/catch,将处置一次性资源"using"?



我正在使用SqlConnectionSqlCommand

例如,如果有任何SqlException,我必须抓住一个例外.

我正在使用using子句并将try/catch block嵌入其中。这是代码:

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 { }
        }
   }
}
我的

问题是,在异常情况下,我的SqlConnectionSqlCommand会被处理掉吗?这是处理它的好方法,还是我应该简单地使用旧时尚的方法使用try/catch/finally块?

using语句只是 try/finally 块的语法快捷方式。所以是的,using中的对象将在引发异常的情况下被释放。换句话说:

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

基本上被编译成:

Foo foo;
try
{
    foo = new Foo();
}
finally
{
    foo.Dispose();
}

在您的情况下,异常会在 using 中捕获,并在您离开 using 块时执行释放。

但是,即使您将 using 块放在try catch外部并抛出异常,也会调用释放。

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 {}
}

您可以在使用块内或使用块外进行 try 捕获。在这两种情况下,SqlConnection 和 SqlCommand 都将被释放。

但是,我更喜欢在使用之外使用 try 捕获所有错误,甚至是对象创建错误。

最新更新