6

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
}
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

3 Answers3

5

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.

C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • i also agree, but the using statment itself is questionable, doesnt it act similar to the try,catch and finally functions? if so, is there a need to wrap the using functions? – lemunk Jan 15 '14 at 09:27
  • But this doesn't speak against: `try{using(...){try{}}}`. Also, you are opening the connection **in** the `using`-statement and not outside, so why should i surround the using itself with a `Try-Catch`, that's a different scope. You are in danger to catch too much which is bad. – Tim Schmelter Jan 15 '14 at 09:32
  • but incase of choosing from one of the above from my point of view second one is better – C Sharper Jan 15 '14 at 09:38
1

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.

DotNetDeveloper
  • 493
  • 1
  • 6
  • 16
1

Personally, I think the best way is - then the connection is closed regardless and you get 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 }
    }
}
owenrumney
  • 1,520
  • 3
  • 18
  • 37