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
Part of the reason they are not in the same scope is because at any point of the try block, you can have thrown the exception. If they were in the same scope, its a disaster in waiting, because depending on where the exception was thrown, it could be even more ambiguous.
At least when its declared outside of the try block, you know for sure what the variable at minimum could be when an exception is thrown; The value of the variable before the try block.
Instead of a local variable, a public property could be declared; this also should avoid another potential error of an unassigned variable. public string S { get; set; }
If the assignment operation fails your catch statement will have a null reference back to the unassigned variable.
You solution is exactly what you should do. You can't be sure that your declaration was even reached in the try block, which would result in another exception in the catch block.
It simply must work as separate scopes.
try
dim i as integer = 10 / 0 ''// Throw an exception
dim s as string = "hi"
catch (e)
console.writeln(s) ''// Would throw another exception, if this was allowed to compile
end try
How could you be sure, that you reached the declaration part in your catch block? What if the instantiation throws the exception?
My thought would be that because something in the try block triggered the exception its namespace contents cannot be trusted - ie referencing the String 's' in the catch block could cause the throw of yet another exception.