简体   繁体   中英

Why does a try/finalize block does not throw CS0165: Use of unassigned local variable compilation error?

Why is it that variant_1 does compile while variant_2 fails with CS0165: Use of unassigned local variable , as expected? I imagined maybe finally initializes unassigned variables to their default, but I do not see that happening.

I ran this code with .NET Core 3.1

static string variant_1()
{
    string str;

    try
    {
        str = "grrr";
    }
    finally
    {

    }

    return str; //no problem ?
}

static string variant_2()
{
    string str;

    try
    {
        str = "grrr";
    }
    catch (Exception ex)
    {

    }

    return str; //does not compile: `CS0165: Use of unassigned local variable`
}

Let's imagine that something bad can happen here:

static string variant_2()
{
    string str;

    try
    {
        //Something bad happens
        str = "grrr";
    }
    catch (Exception ex)
    {

    }

    return str; //does not compile: `CS0165: Use of unassigned local variable`
}

Maybe it's a ThreadAbortException . Maybe it's something else. What happens? Control flow enters the catch and then the remainder of the function executes . str was never assigned.

For the finally case though, if any exception occurs, control flow may enter the finally but then it exits the method . return is never going to be encountered. The only path through that try / finally block that continues to the return is one where no exception occurs in the try part and so the assignment that occurs inside it must have been made.

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