Catching Exception inside Using statement

后端 未结 9 676
不知归路
不知归路 2021-02-04 01:27

I know that Using statement disposes out the object that is being created. Like if I wanted to do something like this:

    Using(SqlConnection conn = new SqlConn         


        
9条回答
  •  有刺的猬
    2021-02-04 02:23

    using doesn't offer any backdoor into the catch.

    Simply expand it manually (no point in having the try/catch inside the using IMO):

    SqlConnection conn = null;
    
    try
    {
        conn = new SqlConnection("");
    }
    catch ...
    {
    
    }
    finally
    {
        if (conn != null)
            conn.Dispose();
    }
    

    I favour this over wrapping the using in a try-catch or embedding a try-catch in the using most of the time to avoid having the code end up with a nested try-catch once compiled. If you only need to cover a very small subset of a large piece of code within a using, however, I'd be more granular and embed it.

提交回复
热议问题