Whats the differenc of using a variable inside the try section and the catch section
string curNamespace;
try
{
curNamespace = "name"; // Works fine
}
catch (Exception e)
{
// Shows use of unassigned local variable
throw new Exception("Error reading " + curNamespace, e);
}
If i use variable inside try section it compiles fine, in catch section i get "Use of unassigned variable"
The compiler is complaining because you may encounter an exception before the value is initialized. Consider the following (very contrived) example:
string curNamespace;
try {
throw new Exception("whoops");
curNamespace = "name"; // never reaches this line
}
catch (Exception e) {
// now curNamespace hasn't been assigned!
throw new Exception("Error reading " + curNamespace, e);
}
The fix would be to initialize curNamespace to some default value outside the try..catch. Have to wonder what you're trying to use it for, though.
It means that variable curNamespace was not initialized before using it in catch scope.
Change your code to this:
string curNamespace = null;
And it will compile fine.
In C#, variables must be initialized before being used. So this is wrong:
string curNamespace; // variable was not initialized
throw new Exception("Error reading " + curNamespace); // can't use curNamespace because it's not initialized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With