This is one mistake that I regularly encounter. Although I manage to get around this one way or another, it really annoys me. In the code snippet below, I want to safely protect against exceptions from 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 create / compile the code, it says
"Using an unrecognized local variable" reader "
Now my question is: if the try statement works without any exceptions, why can't the compiler access the value assigned to the reader inside the try block?
SLearner
source share