Avoiding an “unassigned local variable” defined inside a try-catch block

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?

+7
source share
3 answers

You are using a variable that is assigned in a try / catch block outside this block. You will want to move all the code into a try block.

You can assign null it as @Svexo suggested, but this will throw an exception if there is no stream error.

+10
source

The compiler says use of unassigned variable , because the code after the try / catch block will be executed anyway.

If you have an exception, you will catch it, then run the code after it. That is why you get this error.

You can either

  • assign null local variables and then check if they are null before executing the rest of the code
  • return the function to your catch block.
  • or move all the code into a try block as suggested by @Femaref
+6
source
 WebRequest myRequest = WebRequest.Create(baseUri.OriginalString); WebResponse myResponse = null; Stream myStream= null; StreamReader reader =null; 

This will assign the variables

Edit:

If you do this like this, you should add if outside of your attempt / catch

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

Please note that in your case it is better to place everything in a try / catch block

+2
source

All Articles