c# - 如何避免在 try-catch block 内定义 'Unassigned Local Variable'

标签 c# exception-handling try-catch

这是我经常遇到的一个错误。虽然我设法用某种方式绕过了它,但它真的让我很烦。 在下面的代码片段中,我想防止来自 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());

现在,当我尝试构建/编译代码时,它说

"Use of unassigned local variable 'reader'"

现在我的问题是,如果 try 语句运行顺利且没有抛出任何异常,为什么编译器不能访问 try block 内分配给 reader 的值?

最佳答案

您正在使用一个变量,该变量在 try/catch block 中分配,但位于该 block 之外。您需要将整个代码移动到 try block 中。

您可以像@Svexo 建议的那样将 null 分配给它,但是如果流出错,这将引发异常。

关于c# - 如何避免在 try-catch block 内定义 'Unassigned Local Variable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16999410/

相关文章:

c# - 您最喜欢的 C# 扩展方法是什么? (codeplex.com/extensionoverflow)

c# - 如何从 C# 生成 XML 中的 &quot

python - 有没有比 `except: pass` 更简洁的替代品?

c# - LINQ 条件 where 仅当 prop 不为 null 时

C# 2005 控制台应用程序始终需要提升的权限

php - 处理 Zend Framework 的 Controller 插件中抛出的异常

typescript - typescript 中的 "throw(e)"和 "throw e"有区别吗?

python - 为什么 return 最终给出空字典?

Java 返回值(在 try/catch 子句中)

java - 空指针异常是否会导致 android 应用程序的性能?