try catch异常中的变量

kla*_*ist 2 c# try-catch

什么是在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);

}
Run Code Online (Sandbox Code Playgroud)

如果我在try部分中使用变量,它编译得很好,在catch部分我得到"使用未分配的变量"

Yuc*_*uck 8

编译器抱怨,因为初始化值之前可能会遇到异常.考虑以下(非常人为的)示例:

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

}
Run Code Online (Sandbox Code Playgroud)

修复将初始化curNamespace为一些默认值try..catch.不过,不得不想知道你想要用它做什么.