Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

        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'"

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?

like image 593
SLearner Avatar asked Jun 08 '13 12:06

SLearner


Video Answer


2 Answers

You are using a variable, that is assigned in a try/catch block, outside that block. You'll want to move the whole code into the try block.

You could assign null to it like @Svexo proposed, but this will throw an exception should the stream error out.

like image 98
Femaref Avatar answered Oct 04 '22 17:10

Femaref


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 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 code
  • return the function in your catch block.
  • or move all the code into the try block as suggested @Femaref
like image 30
ppetrov Avatar answered Oct 04 '22 17:10

ppetrov