Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in try catch exception

Tags:

c#

try-catch

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"

like image 832
klashagelqvist Avatar asked Dec 06 '25 06:12

klashagelqvist


2 Answers

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.

like image 116
Yuck Avatar answered Dec 08 '25 19:12

Yuck


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
like image 45
Pablo Santa Cruz Avatar answered Dec 08 '25 19:12

Pablo Santa Cruz