zoukankan      html  css  js  c++  java
  • "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();
                    }

                }

            }
  • 相关阅读:
    1月6日 作业 穷举
    1.4 作业
    12月31日 作业
    12月29日-练习成果
    12月30日作业-<转>字符集编码
    1.22作业
    集合
    泛型
    CPU接口练习 (仅以此程序证明 某个同学真的有毒!有毒!!!)
    继承知识点总结
  • 原文地址:https://www.cnblogs.com/dudu/p/35672.html
Copyright © 2011-2022 走看看