SqlConnection / Command using statement + try / catch block

What is the correct try / catch approach inside use or use 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
}
+4
source share
3 answers

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 right way.

Because with this approach, if there is an exception with a connection to the database, it will come across inside the catch block. But with the first approach he will not.

+5
source

Both are correct in the sense that both will close one-time resources in case of an error.

try-catch, , , , , SqlCommand SQL, .

+1

Personally, I think the best way is then the connection closes independently, and you get the opportunity to handle the exception as you wish

using (SqlConnection connection = CreateSqlConnection(connString))
{
    using (SqlCommand command = CreateSqlCommand()) 
    {
          try { //open connection, execute }
          catch { // log and handle exception }
          finally { // check connection state and close if required }
    }
}
+1
source

All Articles