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.
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");
}
}
}