Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try finally mystery

Consider,

        static void Main(string[] args)
        {
            Console.WriteLine(fun());
        }

        static int fun()
        {
            int i = 0;
            try
            {
                i = 1;
                return i;
            }
            catch (Exception ex)
            {
                i = 2;
                return i;
            }
            finally
            {
                i = 3;
            }
        }

The sample code outputs "1". but the value of i is changed to 3 in finally block. Why wasn't the value of 'i' changed to 3?

Thank you,

like image 874
emeh Avatar asked Nov 29 '22 04:11

emeh


2 Answers

Consider this code- I think the code explains what you are thinking, and how you can make what you think should happen actually happen:

static void Main(string[] args)
{
    int counter = 0;
    Console.WriteLine(fun(ref counter)); // Prints 1
    Console.WriteLine(counter); // Prints 3
}        

static int fun(ref int counter)
{
  try
  {
      counter = 1;
      return counter;
  }
  finally
  {
      counter = 3;
  }
}

With this code you return 1 from the method, but you also set the counter variable to 3, which you can access from outside the method.

like image 116
RichardOD Avatar answered Dec 04 '22 13:12

RichardOD


You have to remember that finally executes after everything else in the try and catch. Place the return statement after the try/catch/finally statement to have it return 3.

like image 20
kemiller2002 Avatar answered Dec 04 '22 11:12

kemiller2002