【问题标题】:Use of unassigned local variable with try-catch-finally通过 try-catch-finally 使用未分配的局部变量
【发布时间】:2017-02-17 00:59:32
【问题描述】:

下面的示例代码在编译时给出了“使用未分配的局部变量'resultCode'”:

    string answer;
    string resultCode;

    try
    {
        resultCode = "a"; 
    }
    catch
    {
        resultCode = "b";
    }
    finally
    {
        answer = resultCode;
    }

我原以为上面的 catch 块应该捕获所有异常,因此在进入 finally 块时不可能取消分配 resultCode。任何人都可以解释一下吗? 谢谢。

编辑:谢谢大家。这个引用文档的答案似乎很好地回答了它:https://stackoverflow.com/a/8597901/70140

【问题讨论】:

标签: c# .net


【解决方案1】:

举例说明:

string answer;
string resultCode;

try
{
    // anything here could go wrong
}
catch
{
    // anything here could go wrong
}
finally
{
    answer = resultCode;
}

此时,编译器无法假设或保证 resultCode 曾被赋值。因此,它会警告您可能会使用未分配的变量。

【讨论】:

  • +1 但我认为值得补充的是,如果 finally 块或所有 trycatch 块肯定分配了一个值,那么它肯定是在整个构造。
【解决方案2】:

添加一些解释,例如,在下面的代码中,变量n是在try块内部初始化的。尝试在 Write(n) 语句中的 try 块之外使用此变量将产生编译器错误。

int n;  
try   
{  
    int a = 0; // maybe a throw will happen here and the variable n will not initialized
    // Do not initialize this variable here.  
    n = 123;  
}  
catch  
{  
}  
// Error: Use of unassigned local variable 'n'.  
Console.Write(n);  

按照 cmets 中的建议,如果您还像这样在 TryCatch 中分配,请尝试在块之后分配

 string answer;
 string resultCode;

 try
 {
    resultCode = "a";
 }
 catch
 {
    resultCode = "b";
 }
 finally
 {
     // answer = resultCode;
 }
 answer = resultCode;

它会编译。

【讨论】:

    【解决方案3】:

    编译器无法保证trycatch 块内的任何代码都将真正运行而不会发生异常。理论上,当您尝试使用 resultCode 时,它的值未分配。

    【讨论】:

      【解决方案4】:

      Visual Studio 不知道您正在为“resultCode”赋值。你需要事先给它一个值。底部的示例代码。

      这作为一个层次结构。 Visual Studio 在 try/catch 中看不到“resultCode”的定义。

      string answer = "";
      string resultCode = "";
      
      try
      {
          resultCode = "a"; 
      }
      catch
      {
          resultCode = "b";
      }
      finally
      {
          answer = resultCode;
      }
      

      【讨论】:

      • 不是,但不管发生什么,都会在try/catch中定义。编译器只是不知道。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      相关资源
      最近更新 更多