try catch块中的变量范围

Dev*_*eak 0 c# scope exception-handling

我在尝试关闭Finally代码块中的文件时遇到错误:

static void Main(string[] args)
{
    try
    {
        StreamReader myReader = new StreamReader("c:\\j\\MyFile1.txt");

        string line = "";

        while (line != null)
        {
            line = myReader.ReadLine();
            Console.WriteLine(line);
        }

        //myReader.Close();
    }
    catch (FileNotFoundException e)
    {
        Console.WriteLine("sorry file not found! {0}", e.Message);
    }
    catch (DirectoryNotFoundException e)
    {
        Console.WriteLine("You have given the wrong path for the file! {0}", e.Message);
    }
    catch (Exception e)
    {
        Console.WriteLine("Sorry you typed in a wrong file name! {0}", e.Message);
    }
    finally
    { 
        myReader.Close();
    }

    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

你需要申报StreamReader上面的try.

话虽这么说,我建议using在这种情况下使用语句而不是try/finally,因为它专门用于资源清理.

using (StreamReader myReader = new StreamReader("c:\\j\\MyFile1.txt"))
{
    try
    {
        string line = "";

        while (line != null)
        {
            line = myReader.ReadLine();
            Console.WriteLine(line);
        }
    }
    catch (FileNotFoundException e)
    {
        Console.WriteLine("sorry file not found! {0}", e.Message);
    }
    catch (DirectoryNotFoundException e)
    {
        Console.WriteLine("You have given the wrong path for the file! {0}", e.Message);

    }
    catch (Exception e)
    {
        Console.WriteLine("Sorry you typed in a wrong file name! {0}", e.Message);
    }
}

Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

这将保证StreamReader关闭,但以更加自我的C#方式这样做. StreamReaderIDisposable.Dispose实施将关闭流


Rya*_*yan 5

在try之前声明你的变量:

StreamReader myReader = null;
Run Code Online (Sandbox Code Playgroud)

然后在try块中设置它们.