我一直在实施相对于 USING 的 TRY-CATCH,如下例所示:
private void someDatabaseMethod(string userName) {
try {
using(var conn = new SqlConnection(connString))
using(var comm = new SqlCommand()) {
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = string.Concat(@"SELECT UserID FROM xxx WHERE UserName = '", userName,@"'");
conn.Open();
object x = comm.ExecuteScalar();
UserID = (x==null)? 0: (int)x;
}
} catch(Exception) {
throw;
}
}
我刚刚看到这个MSDN 示例,它似乎指向 TRY-CATCH 在 USING 中。所以我的示例如下所示:
private void someDatabaseMethod(string userName) {
using(var conn = new SqlConnection(connString))
using(var comm = new SqlCommand()) {
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = string.Concat(@"SELECT UserID FROM xxx WHERE UserName = '", userName,@"'");
try {
conn.Open();
object x = comm.ExecuteScalar();
UserID = (x==null)? 0: (int)x;
} catch(Exception) {
throw;
}
}
}
这是更有效的布局吗?如果是这样,为什么?
额外说明
的原因TRY-CATCH
是重新抛出异常,以便我将其提升到下一个级别 - 所以我想CATCH
在代码中的某个地方。