简体   繁体   English

try catch异常中的变量

[英]Variable in try catch exception

Whats the differenc of using a variable inside the try section and the catch section 什么是在try部分和catch部分中使用变量的不同之处

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" 如果我在try部分中使用变量,它编译得很好,在catch部分我得到“使用未分配的变量”

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 . 修复方法是将curNamespace初始化为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. 这意味着变量curNamespacecatch范围内使用之前未初始化。

Change your code to this: 将您的代码更改为:

string curNamespace = null;

And it will compile fine. 它会编译好。

In C# , variables must be initialized before being used. C#中 ,必须在使用之前初始化变量。 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. 您必须在try块之外分配它。

        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. 您必须首先初始化curNamespace。 Or it "could" be uninitialized in the catch branch. 或者它“可能”在catch分支中未初始化。

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; string curNamespace = String.Empty;

If you change your declaration of curNamespace and assign something to it, it will work: 如果你更改了curNamespace的声明并为其赋值,它将起作用:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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