Catching Exception inside Using statement

后端 未结 9 688
不知归路
不知归路 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:22

    When you embed the using() block inside a try/catch, the using() block will indeed guarantee that Dispose is called. However, if non-managed code anywhere within your using block throws an exception, using() will just eat it and it won't reach your catch. Use try/catch inside the using() block, skip using() and do a try/catch/finally, or use the odd "using() try" syntax with a catch block (which leaves you with an odd number of brackets and is likely to confuse the heck out of mid-level programmers who later encounter it.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 02:26

    There's nothing special about code written inside a using block - just use a try.catch to handle exceptions:

    using(SqlConnection conn = new SqlConnection(connString))
    {
        try
        {
            conn.Open();
            // do more stuff here......
    
        }
        catch(SqlException sqlEx)
        {
           // log error and possibly show to user in a MessageBox or something else
        }
    }
    

    The using(...) { ... } block itself is designed only to ensure that the resource / object it "encapsulates" is properly disposed of when it's no longer needed. There's is nothing you can do with the using statement itself to make it handle errors.

    So if you expect that just creating the object could fail, then you'd have to put the entire using block inside the try ... catch block , or fall back to a try ... catch ... finally block and ensure proper disposal yourself (as Adam suggested in his answer).

    0 讨论(0)
提交回复
热议问题