Catching Exception inside Using statement

后端 未结 9 680
不知归路
不知归路 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: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).

提交回复
热议问题