C# using statement catch error

后端 未结 16 1324
轻奢々
轻奢々 2021-01-30 14:06

I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:

 using (SqlComma         


        
16条回答
  •  执念已碎
    2021-01-30 14:49

    If your code looks like this:

    using (SqlCommand cmd = new SqlCommand(...))
    {
      try
      {
        /* call stored procedure */
      }
      catch (SqlException ex)
      {
        /* handles the exception. does not rethrow the exception */
      }
    }
    

    Then I would refactor it to use try.. catch.. finally instead.

    SqlCommand cmd = new SqlCommand(...)
    try
    {
      /* call stored procedure */
    }
    catch (SqlException ex)
    {
      /* handles the exception and does not ignore it */
    }
    finally
    {
       if (cmd!=null) cmd.Dispose();
    }
    

    In this scenario, I would be handling the exception so I have no choice but to add in that try..catch, I might as well put in the finally clause and save myself another nesting level. Note that I must be doing something in the catch block and not just ignoring the exception.

提交回复
热议问题