0

I have the following c# code:

   public class Program
   {
        static void Main()
        {
            int i = 123;
            string s = "Some string";
            object obj = s;

            try
            {
                // Invalid conversion; 
                i = (int)obj;

                // The following statement is not run.
                Console.WriteLine("WriteLine at the end of the try block.");
            }
            finally
            {
                Console.WriteLine("\n Finally Block executed !!!");
            }
        }
    }

When an exception occur the program crashes without passing control to the finally block as it is understood that finally block must be executed to release the resources gained in try block.

Kifayat Ullah
  • 579
  • 1
  • 5
  • 14
  • As you can see from [this fiddle](https://dotnetfiddle.net/wf8DN9), this isn't true. Provide a [mcve] that demonstrates your problem. – Charles Mager Oct 01 '16 at 08:12
  • Yes it would work on dotnetfiddle but while i ran it on visual studio 2013 it throws the following exception without passing control to finally block first, as in your case. Unhandled Exception: System.InvalidCastException: Specified cast is not valid. at exceptionHandling.Program.Main() in c:\Users\Kifayat\Desktop\Learn\excepti onHandling\exceptionHandling\Program.cs:line 69 – Kifayat Ullah Oct 01 '16 at 08:41
  • 2
    It will still execute it. What you're likely seeing is that Visual Studio breaks on unhanded exceptions, which will be before the finally block is executed. Hit 'Run' again and the finally block will execute. – Charles Mager Oct 01 '16 at 08:47

1 Answers1

0

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

Ref : https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

To validate this, I tried your sample like this and it executed finally block. Try this :

public class MainClass {
public static void Main()
{
    try {
        Invalid();
    }
    catch (Exception ext) {
        Console.Write(ext.Message);
    }
}

public static void Invalid()
{
    string message = "new string";
    object o = message;
    try
    {
        int i = (int)o;
    }
    finally
    {
        Console.WriteLine("In finally");
    }
 }
}