Click here to Skip to main content
15,917,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Read a article about Finally execution if throw a exception. but when i am using same sample of code then finally block is not executing.

How to: Use Finally Blocks | Microsoft Docs[^]

What I have tried:

class Program
    {
        static void Main(string[] args)
        {

            new Program().Mehtod();
            Console.Read();
        }

        public void Mehtod()
        {
            int[] array1 = { 0, 0 };
            int[] array2 = { 0, 0 };

            try
            {
                Array.Copy(array1, array2, -1);
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine("Error: {0}", e);
                throw;
            }
            finally
            {
                Console.WriteLine("This statement is always executed.");
            }
        }
    }
Posted
Updated 12-May-21 4:33am

1 solution

Yes it does always execute. A block like this actually gets compiled into something like the below:
C#
try
{
  try
  {
    ..
  }
  catch (..)
  {
    ..
  }
}
finally
{
  ..
}

If you run your code directly in Visual Studio you probably won't see the finally block because the console window will close almost immediately once the throw; line is called, not giving you enough time to see the printed message. However, if you actually run the application from a Command Prompt, you should see the exception printed out and then see the code in the finally block.
 
Share this answer
 
Comments
Siddharth Rai 12-May-21 10:43am    
Yes, it is working. i was running via visual studio in debug mode in that case it stuck at the throw statement and start showing exception.
once run the exe directly then i am able to see the finally block execution.
thank you so much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900