"finally"使用注意

先请大家看下面一段代码:
public static void Test(string fileName)
        
{
            
string fileName;
            System.IO.StreamReader sr
=null;
            
try
            
{
                sr
=new System.IO.StreamReader(fileName);                
            }

            
finally
            
{
                sr.Close();
            }

        }


以前我一直采用上面的方法关闭StreamReader, 我从没想到这样的写法在运行时会引起问题。今天我就遇到了莫明其妙的“未将对象引用设置到对象的实例”异常。因为这个异常很难跟踪,一开始我总是怀疑sr=new System.IO.StreamReader(fileName);后面的代码引起的异常,可是我将那部分代码全部注释, 还是有这个异常。后来,我注释掉sr.Close();才发现引起异常的真正原因。
原来在sr=new System.IO.StreamReader(fileName); 中,由于fileName路径不对,找不到相应的文件,抛出了异常,此时sr应该是null值,而在finally中执行sr.Close()就会引起“未将对象引用设置到对象的实例”异常。
正确的代码应该是这样:
public static void Test(string fileName)
        
{
            
string fileName;
            System.IO.StreamReader sr
=null;
            
try
            
{
                sr
=new System.IO.StreamReader(fileName);                
            }

            
finally
            
{
                
if(sr!=null)
                
{
                    sr.Close();
                }

            }

        }
posted @ 2004-08-22 17:33  dudu  阅读(4822)  评论(21编辑  收藏  举报