在进行IO工作时,我编写代码以预期出现异常。
SqlConnection conn = null;
SqlCommand cmd = null;
try
{
conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)
cmd = new SqlCommand(reportDataSource, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
conn.Open();
DataSet dset = new DataSet();
new SqlDataAdapter(cmd).Fill(dset);
this.gridDataSource.DataSource = dset.Tables[0];
}
catch(Exception ex)
{
Logger.Log(ex);
throw;
}
finally
{
if(conn != null)
conn.Dispose();
if(cmd != null)
cmd.Dispose();
}
编辑:明确地说,我避免在这里使用using块,因为我认为在这样的情况下记录日志非常重要。经验告诉我,你永远不知道会出现什么奇怪的异常。在这种情况下记录日志可能有助于检测死锁,或查找模式更改影响你代码库中未经过多次测试和使用的部分,或其他任何问题。
编辑2:在这种情况下,人们可以争论一个using块是否可以包装try/catch,并且这是完全有效且功能相等的。这实际上归结为个人喜好。你想避免额外的嵌套以换取处理自己的资源回收吗?还是你愿意承受额外的嵌套以获得自动回收?我觉得前者更加简洁,所以我这样做。但是,如果我发现代码库中有后者,我不会重写它。
编辑3:我真的非常希望微软创建一个更明确的using()版本,在这种情况下使其更具直观性并提供更多灵活性。考虑以下虚构代码:
SqlConnection conn = null;
SqlCommand cmd = null;
using(conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString),
cmd = new SqlCommand(reportDataSource, conn)
{
conn = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString);
cmd = new SqlCommand(reportDataSource, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
cmd.Open();
DataSet dset = new DataSet();
new SqlDataAdapter(cmd).Fill(dset);
this.gridDataSource.DataSource = dset.Tables[0];
}
catch(Exception ex)
{
Logger.Log(ex);
throw;
}
使用using语句只是创建了一个带有Dispose()调用的try/finally块。为什么不给开发人员提供一种统一的方法来处理释放和异常?
using
来处理异常存在缺陷。我同意 @Jason Jackson 的观点,编译时using
会被转换为try/finally
。如果我想捕获异常,在using
中添加try/catch
将会生成两个try
语句块,这会影响性能。更糟糕的是,.Dispose()
方法通常不会关闭连接,直到调用.Close()
或等待垃圾回收。那么,为什么不直接写上try/catch/finally
呢?我将在final
块中检查空引用、连接是否打开并关闭和销毁它。这更加合适和更好。 - CallMeLaNN