المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Nested try/catch blocks



C# Programming
06-19-2009, 01:01 PM
I'm somewhat hesitating about using nested try/catch blocks.

The situation which makes me think about is the following situation. Some sample code to illustrate:

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlTransaction trans = conn.BeginTransaction();

try
{
string query = "query goes here";
SqlCommand command = new SqlCommand(query, conn, trans);
// add parameters
command.ExecuteNonQuery();
trans.Commit();
}
catch
{
trans.Rollback();
}
finally
{
if(conn != null)
{
conn.Close();
conn.Dispose();
}
}
This block has 1 try/catch block but the problem resides in the "conn.Open();" line. When there is a network error the conn.Open() will throw an exception. Putting the conn.Open() in the try/catch block will invalidate the code which now resides in the catch/finally clauses.

So I can use 2 sequential try/catch blocks or a nexted construction. What do you people think?

The consumer isn't a moron; she is your wife.