Search code examples
c#try-catchfinally

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,


Solution

  • 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.