I've been implementing TRY-CATCH relative to USING like the following example:
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;
}
}
I've just seen this MSDN EXAMPLE which seems to point towards the TRY-CATCH being within the USING. So my example would look like the following:
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;
}
}
}
Is this a more efficient layout? If so, why?
EXTRA ADDITIONAL NOTE
The reason for the TRY-CATCH
is to re-throw the exception so that I bubble it up to the next level - so I'd like to have a CATCH
somewhere in the code.