代码之家  ›  专栏  ›  技术社区  ›  char m

C:是否都在使用并尝试最终使用streamreader处理错误选项?

  •  0
  • char m  · 技术社区  · 14 年前

    想想这个:

    StreamReader reader = null;
    
    try
    {
        reader = new StreamReader(_fileName);
    }
    catch
    {
        //show error that file not found
        reader.Dispose();
        return false;
    }
    
    try
    {
        //code to read file
    }
    catch
    {
       //show error badly formed file
    }
    finally
    {
        reader.Dispose();
    }
    //return 
    

    当无法打开文件时,上面的代码不起作用,因为它调用Dispose for null,从而导致异常。

    我不想使用,因为我想在打开和读取文件时区分问题。这可以用上百万种不同的捕获量来实现,但我不想这样做。另外,如果使用与try finally相同,那么“hidden dispose”是否仍会引发不需要的异常?当我只需要捕获一个打开它的异常和一个读取它的异常时,哪种方法是最好的?

    谢谢&br-Matti

    4 回复  |  直到 14 年前
        1
  •  6
  •   Oded    14 年前

    最好用 using statement :

    using(StreamReader reader = new StreamReader(_fileName))
    {
    }
    

    编译器将为您创建正确的释放语义。

    你仍然可以使用 try 有了这个,不用担心自己处理它:

    try
    {
        using(StreamReader reader = new StreamReader(_fileName))
        {
             try
             {
                //code to read the file
             }
             catch
             {
                //show error badly formed file
             }
        }
    }
    catch
    {
        // show error that file not found
    }
    
        2
  •  2
  •   Liviu Mandras    14 年前

    如果您检查,您的代码是正确的 reader 在对其调用任何方法之前,如果读卡器位于何处,则返回空值。

    using语句不是强制性的,但也是可取的。

        3
  •  2
  •   Marnix van Valen    14 年前

    在释放读卡器之前,应该检查它是否为空。就像这样:

    StreamReader reader = null;
    try
    {
        //code to read file
    }
    catch
    {
       //show error badly formed file
    }
    finally
    {
      if( null != reader )
      {
        reader.Dispose();
      }
    }
        4
  •  1
  •   Oded    14 年前

    这个 StreamReader 可以抛出以下异常,这样您就可以相应地处理这些异常:

    ArgumentException
    ArgumentNullException
    FileNotFoundException
    DirectoryNotFoundException
    NotSupportedException
    ArgumentOutOfRangeException