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
While in your example it is weird that it does not work, take this similar one:
try
{
//Code 1
String s = "1|2";
//Code 2
}
catch
{
Console.WriteLine(s.Split('|')[1]);
}
This would cause the catch to throw a null reference exception if Code 1 broke. Now while the semantics of try/catch are pretty well understood, this would be an annoying corner case, since s is defined with an initial value, so it should in theory never be null, but under shared semantics, it would be.
Again this could in theory be fixed by only allowing separated definitions (String s; s = "1|2";
), or some other set of conditions, but it is generally easier to just say no.
Additionally, it allows the semantics of scope to be defined globally without exception, specifically, locals last as long as the {}
they are defined in, in all cases. Minor point, but a point.
Finally, in order to do what you want, you can add a set of brackets around the try catch. Gives you the scope you want, although it does come at the cost of a little readability, but not too much.
{
String s;
try
{
s = "test";
//More code
}
catch
{
Console.WriteLine(s);
}
}