Using an unassigned local variable with try-catch-finally

The code example below gives "Using the unrecognized local variable" resultCode "when compiling:

    string answer;
    string resultCode;

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

I would think that the above catch block should catch all exceptions, and therefore it is impossible that resultCode was not assigned at the time the finally block is entered. Can anyone shed some light? Thank.

EDIT: Thanks to everyone. This answer, which cites the documentation, seems to be responding well to it: https://stackoverflow.com/a/166778/

+4
source share
4 answers

To illustrate:

string answer;
string resultCode;

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

, resultCode - . , .

+2

. , n try. try Write (n) .

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

, Try Catch, ,

 string answer;
 string resultCode;

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

.

+1

The compiler cannot guarantee that any code inside the blocks tryor catchwill be executed without exception. Which leaves the theoretical value resultCodeas unassigned when you try to use it.

0
source

Visual Studio does not know that you are assigning a "resultCode" value. You have to give it meaning before hand. Sample code below.

It is like a hierarchy. Visual Studio does not see the definition of "resultCode" in try / catch.

string answer = "";
string resultCode = "";

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

Source: https://habr.com/ru/post/1670005/


All Articles