I am bit confused regarding the finally block. I know that finally block gets executed no matter if there is an exception or not.
I have got 2 scenarios :-
1) If there is an exception in try block and I have not written any catch block for this try block, but I have a finally block, then will the finally block gets executed? Does finally block executed if the exception is unhandled?
Below is an example code :-
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
//catch (Exception ex)
//{
// int divide = 12 / x;
// Console.WriteLine(ex.Message);
//}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
2) Will the finally block get executed if there is an exception in catch block? Below is the sample code :-
static void Main(string[] args)
{
int x = 0;
try
{
int divide = 12 / x;
}
catch (Exception ex)
{
int divide = 12 / x; // this will throw exception in catch block
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("I am finally block");
}
Console.ReadLine();
}
I have tried these codes and I don't see the finally block getting executed. Please explain me why the finally block is not executed.