I am quite confused with how exceptions are getting thrown in C#. If an exception occurs, in the try block, 1.it gets thrown to the catch block, 2. If and only if the catch block catches it the finally block will be executed. 3. The finally block gets executed last, provided the catch statement caught it.
However, when I try to run the program below, the output is A,B not BA.Is there something wrong with my understanding? Thank you.
class Program
{
public static void Main(string[] args)
{
try
{
int a = 2;
int b = 10 / a;
try
{
if (a == 1)
a = a / a - a;
if (a == 2)
{
int[] c = { 1 };
c[8] = 9;
}
}
finally
{
Console.WriteLine("A");
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("B");
}
Console.ReadLine();
}
}
The exception occurs in a==2, and I know the outer catch will catch this exception. However, the finally is being executed first? Any reason as to why this is showing?
edited
From C# docs we know Finally block gets executed whether or not an exception has occured.
However, my finally block never gets executed and in return I am getting a run time error
class Program
{
public static void Main(string[] args)
{
try
{
int a = 2;
int b = 10 / a;
try
{
if (a == 1)
a = a / a - a;
if (a == 2)
{
int[] c = { 1 };
c[8] = 9;
}
}
finally
{
Console.WriteLine("A");
}
}
finally{
Console.WriteLine("finally");
}
Console.ReadLine();
}
}
Ain console always andBif exception is of type IndexOutOfRangeException.catchclause is found, the system prepares to transfer control to the first statement of thecatchclause. Before execution of thecatchclause begins, the system first executes, in order, anyfinallyclauses that were associated withtrystatements more nested that than the one that caught the exception.However, my finally block never gets executed and in return I am getting a run time errorThat is not true. They are executed AND you get unhandled exception error on runtime. See here: Test. You can see A and finally printed out and then an exception.