Ali
Ali

Reputation: 1409

Variable declared inside catch block conflicts with variable declared outside (after catch block)

My understanding is that you cannot access a variable outside its scope (which typically starts from the point of declaration and ends at the brace of the same block it is declared in).

Now consider the following code:

void SomeMethod()
{
   try
   {
      // some code
   }
   catch (Exception ex)
   {
      string str = "blah blah"; // Error: Conflicting variable `str` is defined below
      return str;
   }

   string str = "another blah"; // Error: A local variable named `str` cannot be defined in this scope  because it would give a different meaning to `str`, which is already used in the parent or current scope to denote something else.
   return str;
}

I changed the code to the following:

void SomeMethod()
{
   try
   {
      // some code
   }
   catch (Exception ex)
   {
      string str = "blah blah";
      return str;
   }

   str = "another blah"; // Error: Cannot resolve symbol 'str'
   return str;
}

Is there any explanation that why it is happening?

Upvotes: 1

Views: 122

Answers (1)

waka
waka

Reputation: 3407

As you have already stated: The declaration inside a scope is only valid for said scope. If you declare anything inside the try or catch blocks, it will only be valid there. Compare:

try
{
    string test = "Some string";
}
catch
{
    test = "Some other string";
}

will result in the exact same error.

For your code snippet to work, you need to declare the string outside the try-catch-block:

void SomeMethod()
{
   string str = String.Empty;
   try
   {
      // some code
   }
   catch (Exception ex)
   {
      str = "blah blah";
      return str;
   }

   str = "another blah";
   return str;
}

Upvotes: 3

Related Questions