klashagelqvist
klashagelqvist

Reputation: 1261

Variable in try catch exception

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"

Upvotes: 3

Views: 19039

Answers (6)

Diego
Diego

Reputation: 18349

If you change your declaration of curNamespace and assign something to it, it will work:

string curNamespace = null; /* ASSIGN SOMETHING HERE */
try
{
  curNamespace = "name";
}
catch (Exception e)
{
throw new Exception("Error reading " + curNamespace, e);

}

Upvotes: 0

kenik
kenik

Reputation: 1798

You have to assign something to the variable because it is not guaranteed that the variable will hold something when it's used.

You can do with:

string curNamespace = String.Empty;

Upvotes: 0

BlueM
BlueM

Reputation: 6888

You have to initialize curNamespace first. Or it "could" be uninitialized in the catch branch.

Upvotes: 0

Yuck
Yuck

Reputation: 50825

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.

Upvotes: 11

Mikael Härsjö
Mikael Härsjö

Reputation: 1036

You have to assign it outside the try block.

        string curNamespace = string.Empty; // or whatever

        try
        {
            curNamespace = "name";
        }
        catch (Exception e)
        {
            throw new Exception("Error reading " + curNamespace, e);
        }

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

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

Upvotes: 3

Related Questions