[导入]How to keep a local variable in scope across a try and catch block?


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.

 

 

[author: SantoshZ] [导入]How to keep a local variable in scope across a try and catch block?





本文转自斯克迪亚博客园博客,原文链接:http://www.cnblogs.com/sgsoft/archive/2004/09/22/45400.html,如需转载请自行联系原作者
上一篇:实用 | Apache Kudu读写路径


下一篇:云计算与钉钉相结合——钉钉成功案例分析