简体   繁体   English

如何避免在 try-catch 块中定义“未分配的局部变量”

[英]How to avoid 'Unassigned Local Variable' defined inside a try-catch block

This is one error that I regularly face.这是我经常面临的一个错误。 Although I manage to circumvent it using some way or another, it really annoys me.虽然我设法通过某种方式绕过它,但它真的让我很恼火。 In the code snippet below, I want to safe guard against exceptions from myRequest.GetResponse()在下面的代码片段中,我想防止来自 myRequest.GetResponse() 的异常

        WebRequest myRequest = WebRequest.Create(baseUri.OriginalString);
        WebResponse myResponse;
        Stream myStream;
        StreamReader reader;
        try
        {
            myResponse = myRequest.GetResponse();
            myStream = myResponse.GetResponseStream();
            reader = new StreamReader(myStream);
        }
        catch (WebException status)
        {
            txtConsole.AppendText("Error in GetLinks::WebException\n" + status.Response);
            txtConsole.AppendText(Environment.NewLine);
        }
        catch
        {
            txtConsole.AppendText("Some error in GetLinks");
            txtConsole.AppendText(Environment.NewLine);
        }

        Regex regex = new Regex(@"\s*(?i)href\s*=\s*(\""([^""]*\"")|'[^']*'|([^'"">\s]+))", RegexOptions.IgnoreCase);
        MatchCollection splits = regex.Matches(reader.ReadToEnd());

Now, when I try to build/compile the code, it says现在,当我尝试构建/编译代码时,它说

"Use of unassigned local variable 'reader'" “使用未赋值的局部变量‘reader’”

Now my question, if try statement runs smoothly without any exceptions being thrown, why can't the compiler access the value assigned to reader inside the try block?现在我的问题是,如果 try 语句顺利运行而没有抛出任何异常,为什么编译器不能访问 try 块内分配给 reader 的值?

You are using a variable, that is assigned in a try/catch block, outside that block.您正在使用一个变量,该变量在该块之外的 try/catch 块中分配。 You'll want to move the whole code into the try block.您需要将整个代码移动到 try 块中。

You could assign null to it like @Svexo proposed, but this will throw an exception should the stream error out.您可以像@Svexo 建议的那样为它分配null ,但是如果流出错,这将引发异常。

The compiler says use of unassigned variable because the code after the try/catch block will be executed anyway.编译器说use of unassigned variable因为无论如何都会执行 try/catch 块之后的代码。

If you have an exception, you catch it, then you run the code after it.如果你有一个异常,你捕捉它,然后在它之后运行代码。 That's why you get this error.这就是您收到此错误的原因。

You can either你可以

  • assign null to the local variables and then test if they're null before executing the rest of the codenull分配给局部变量,然后在执行其余代码之前测试它们是否为 null
  • return the function in your catch block.返回 catch 块中的函数。
  • or move all the code into the try block as suggested @Femaref或按照建议将所有代码移动到 try 块中@Femaref
 WebRequest myRequest = WebRequest.Create(baseUri.OriginalString);
 WebResponse myResponse = null;
 Stream myStream= null;
 StreamReader reader =null;

This will assign the variables这将分配变量

Edit:编辑:

If you do it like this you should add an if outside your try/catch如果你这样做,你应该在你的 try/catch 之外添加一个 if

if(reader != null)
{
        Regex regex = new Regex(@"\s*(?i)href\s*=\s*(\""([^""]*\"")|'[^']*'|([^'"">\s]+))", RegexOptions.IgnoreCase);
        MatchCollection splits = regex.Matches(reader.ReadToEnd());
}

Do note in your case its better to put everything in the try/catch block请注意,在您的情况下,最好将所有内容都放在 try/catch 块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM