leviathanbadger
leviathanbadger

Reputation: 1712

What happens to the returned value after exception is thrown in finally block?

I wrote the following test code, even though I was pretty sure what would happen:

static void Main(string[] args)
{
    Console.WriteLine(Test().ToString());
    Console.ReadKey(false);
}

static bool Test()
{
    try
    {
        try
        {
            return true;
        }
        finally
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        return false;
    }
}

Sure enough, the program wrote "False" to the console. My question is, what happens to the true that is originally returned? Is there any way to get this value, in the catch block if possible, or in the original finally block if not?

Just to clarify, this is only for educational purposes. I would never make such a convoluted exception system in an actual program.

Upvotes: 9

Views: 1848

Answers (1)

Ry-
Ry-

Reputation: 225164

No, it's not possible to get that value, because only a bool is returned, after all. You can set a variable, though.

static bool Test()
{
    bool returnValue;

    try
    {
        try
        {
            return returnValue = true;
        }
        finally
        {
            throw new Exception();
        }
    }
    catch (Exception)
    {
        Console.WriteLine("In the catch block, got {0}", returnValue);
        return false;
    }
}

It's messy, though. And for education purposes, the answer is no.

Upvotes: 5

Related Questions