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

倖福魔咒の 提交于 2019-12-21 16:47:14

问题


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
}

回答1:


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.




回答2:


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.




回答3:


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 }
    }
}


来源:https://stackoverflow.com/questions/21133397/sqlconnection-command-using-statement-try-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!