0

I`ve used a function to open sql connection and generate a command.So I don`t use using for them. But what happens if I get an exception ?while catch the exception nedd I explicitly dispose them?

1
  • Yes, in particular the SqlConnection but also the SqlCommand. However it is not clear why opening a SqlConnection in function precludes the using statement. Commented Jan 14, 2014 at 14:59

1 Answer 1

2

using translates into try-finally block. If you don't want to use using statement then you can mimic the same using try-finally, in your case with catch just have finally block and dispose the connection there. Something like:

{
    SqlConnection conn = new SqlConnection("your connection string");
    try
    {
        //your code
    }
    catch (SqlException se)
    {
        //handle particular exception first
    }
    catch (Exception ex)
    {

        //handle all other exceptions
    }
    finally
    {
        if (conn != null)
            conn.Dispose();
    }
}

That will ensure the disposal of connection in case of an exception and normal flow (when no exception occurs)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.