开发者

If I catch exceptions inside a using statement for a SqlConnection, does the using still handle closing and disposing my connection?

I'm going through some old C#.NET code in an ASP.NET application making sure that all SqlConnections are wrapped in using blocks.

This piece of code used to open cn and da and close and dispose them in both the catch block and the end of the method. I added the usings and can't figure out for certain if the using blocks still handle disposing of the connection if an exception is thrown in the try and caught in the catch. This question seems to suggest that it does.

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
    using (SqlDataAdapter da = new SqlDataAdapter())
    {
        // do some stuff
        try
        {
            // do stuff that might throw exceptions
        }
        catch (catch (System.Exception e)
        {
            //return something here
            // can I ditch these because the using's handle it?      
            da.Dispose();
            cn.Close();
            cn.Dispose();
            return msg;
        }
    }
} 
开发者_如何学Python


Yes, they will. They're basically turned into a finally block.

So something like this:

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
....
}

is really turned into:

SqlConnection cn = new SqlConnection(Global.sDSN)
try
{
....
}
finally
{
    cn.Dispose();
}

more or less - and the finally block is always executed, no matter what might have happened before in the try {.....} block.


When you use a using clause this is what's happening:

myobject = new object();
try{ 
   // do something with myobject
}finally{
   myobject.Dispose();
}

Hope this helps, Best regards, Tom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜