简体   繁体   中英

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"

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

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);
        }

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

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;

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM