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();
                    }

                }

            }
  • 相关阅读:
    Servlet3.0-使用注解定义Servlet
    poj 1256 Anagram—next_permutation的神奇应用
    poj 1664 放苹果 (划分数)
    poj 1011 Sticks
    poj和hdu部分基础算法分类及难度排序
    Notepad++支持jQuery、html5、css3
    Codeforces Round #395 (Div. 2) C. Timofey and a tree
    Codeforces Round #390 (Div. 2) D. Fedor and coupons
    bazel-编译动态库
    bazel-编译多目标
  • 原文地址:https://www.cnblogs.com/dudu/p/35672.html
Copyright © 2011-2022 走看看