Search code examples
c#sqlexceptionusing-statement

sqlConnection/Command using statement + try/catch block


What is a correct approach try/catch inside using or using inside try/catch?

using (SqlConnection connection = CreateSqlConnection(connString))
{
               using (SqlCommand command = CreateSqlCommand()
               {
                   try{//open connection + execute command + do something else}
                   catch{//do something}
               }
}

vs.

try
{
    using (SqlConnection connection = CreateSqlConnection(connString))
    {
               using (SqlCommand command = CreateSqlCommand()
               {
                   //open connection + execute command + do something else
               }
    }
}
catch
{
 //do something
}

Solution

  • From my point of view:

    try
    {
        using (SqlConnection connection = CreateSqlConnection(connString))
        {
                   using (SqlCommand command = CreateSqlCommand()
                   {
                       //open connection + execute command + do something else
                   }
        }
    }
    catch
    {
     //do something
    }
    

    Above is the correct way.

    Because , with this approach if there is exception with connection to database, that will get caught inside catch block.. But with first approach, it will not.