In C# and in Java (and possibly other languages as well), variables declared in a \"try\" block are not in scope in the corresponding \"catch\" or \"finally\" blocks. For e
@burkhard has the question as to why answered properly, but as a note I wanted to add, while your recommended solution example is good 99.9999+% of time, it is not good practice, it is far safer to either check for null before using something instantiate within the try block, or initialize the variable to something instead of just declaring it before the try block. For example:
string s = String.Empty;
try
{
//do work
}
catch
{
//safely access s
Console.WriteLine(s);
}
Or:
string s;
try
{
//do work
}
catch
{
if (!String.IsNullOrEmpty(s))
{
//safely access s
Console.WriteLine(s);
}
}
This should provide scalability in the workaround, so that even when what you're doing in the try block is more complex than assigning a string, you should be able to safely access the data from your catch block.