【问题标题】:sqlConnection/Command using statement + try/catch block [duplicate]sqlConnection/Command 使用语句 + try/catch 块 [重复]
【发布时间】:2014-02-03 16:25:33
【问题描述】:

什么是 try/catch inside using 或 using inside try/catch?

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

对比

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

【问题讨论】:

    标签: c# sql exception using-statement


    【解决方案1】:

    在我看来:

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

    以上是正确的方法。

    因为,如果使用这种方法,如果与数据库的连接出现异常,则会在 catch 块中被捕获。但使用第一种方法,它不会。

    【讨论】:

    • 我也同意,但是 using 语句本身是有问题的,它的作用不类似于 try、catch 和 finally 函数吗?如果是这样,是否需要包装使用函数?
    • 但这并不反对:try{using(...){try{}}}。此外,您在using-statement 中打开连接in 而不是在外部,那么为什么我应该用Try-Catch 包围使用本身,这是一个不同的范围。你有危险捕捉太多这是不好的。
    • 但是从我的角度来看,如果从上述之一中选择第二个更好
    【解决方案2】:

    两者都是正确的,因为两者都会在发生错误时关闭一次性资源。

    try-catch-statement 的放置位置应取决于您想对该信息做什么,即,如果您想对有关 SqlCommand 本身的错误或更一般的 SQL 错误做出反应,这也可能涉及连接。

    【讨论】:

      【解决方案3】:

      就个人而言,我认为最好的方法是 - 然后关闭连接,您可以根据需要处理异常

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

      【讨论】:

        猜你喜欢
        • 2016-03-15
        • 2010-11-25
        • 2014-06-18
        • 1970-01-01
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        相关资源
        最近更新 更多