Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlConnection/Command using statement + try/catch block [duplicate]

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
}
like image 778
Yakov Avatar asked Jan 15 '14 09:01

Yakov


2 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 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.

like image 147
C Sharper Avatar answered Sep 30 '22 14:09

C Sharper


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

Where you place the try-catch-statement should depend on what you want to do with that information, i.e. if you want to react to an error concerning the SqlCommand itself or a more general SQL-error, that could also involve the connection.

like image 22
DotNetDeveloper Avatar answered Sep 30 '22 13:09

DotNetDeveloper