C# – Why Are Variables in Try Block Limited in Scope?

cerror handlinglanguage-featuresnet

I want to add error handling to:

var firstVariable = 1;
var secondVariable = firstVariable;

The below won't compile:

try
{
   var firstVariable = 1;
}
catch {}

try
{
   var secondVariable = firstVariable;
}
catch {}

Why is it necessary for a try catch block to affect the scope of variables as other code blocks do? Consistency-sake aside, wouldn't it make sense for us to be able to wrap our code with error handling without the need to refactor?

Best Answer

What if your code was:

try
{
   MethodThatMightThrow();
   var firstVariable = 1;
}
catch {}

try
{
   var secondVariable = firstVariable;
}
catch {}

Now you'd be trying to use an undeclared variable (firstVariable) if your method call throws.

Note: The above example specifically answers the original question, which states "consistency-sake aside". This demonstrates that there are reasons other than consistency. But as Peter's answer shows, there is also a powerful argument from consistency, which would for sure have been a very important factor in the decision.