Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
leviathanbadger Avatar asked Mar 07 '12 00:03

leviathanbadger


People also ask

What happens if an exception is thrown in finally block?

Some resource cleanup, such as closing a file, needs to be done even if an exception is thrown. To do this, you can use a finally block. A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.

What happens when we put a return statement in a try block will the final block be executed or not?

Yes, the finally block will be executed even after a return statement in a method.

What will happen when catch and finally block return value?

When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.

Can we return value in finally block?

Yes, we can write a return statement of the method in catch and finally block. There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.


1 Answers

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.

like image 76
Ry- Avatar answered Oct 28 '22 20:10

Ry-