KAOIKI'S Technology WORLD

ALL Technology about Computer Development

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

The following code won't work, because conn goes out of scope before you enter the catch block.

       try

        {

            Connection conn = new Connection();

            conn.Open();

        }

        catch

        {

            if (conn != null) conn.Close();

        }

 

The fix is simple - just declare conn before entering the try block

 

        Connection conn = null; // Note the assignment to null to avoid error CS0165 - Use of possibly unassigned local variable 'conn'.

        try

        {

            conn = new Connection();

            conn.Open();

        }

        catch

        {

            if (conn != null) conn.Close();

        }

 

Of course, for this particular example, you could wrap the Connection class in one that implements IDisposable (if it does not already), so that you could then use a using statement instead of extending the scope of the local.

posted on 2004-10-13 02:34  KAOIKI  阅读(516)  评论(0编辑  收藏  举报