There is a try/catch/finally
block within the for
or foreach
loop.
What will happen if there is a break
statement within the try
block?
Will finally
block be executed?
There is a try/catch/finally
block within the for
or foreach
loop.
What will happen if there is a break
statement within the try
block?
Will finally
block be executed?
Yes, finally blocks hit even if you have a jump statement such as break
.
Typically, the statements of a finally block run when control leaves a try statement.The transfer of control can occur as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.
It will. You can try to run the following example
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
try
{
Console.WriteLine(i);
if (i == 3)
break;
}
catch (Exception e)
{
}
finally
{
Console.WriteLine("finally");
}
}
Console.ReadKey();
}
Yes it will get hit. Here's a sample code you can try.
var intList = new List<int>{5};
foreach(var intItem in intList)
{
try
{
if(intItem == 5)
break;
}
catch(Exception e)
{
Console.WriteLine("Catch reached");
}
finally
{
Console.WriteLine("Finally reached");
}
}
Output : Finally Reached
YES it will hit finally
. Try Me.
Below will confirm my answer:
using System;
public class Program
{
public static void Main()
{
for (int i = 0; i < 100; i++)
{
try
{
if (i == 10)
{
break;
}
Console.WriteLine(i);
}
catch
{
Console.WriteLine("Catch");
}
finally
{
Console.WriteLine("finally");
}
}
}
}
Output:
0
finally
1
finally
2
finally
3
finally
4
finally
5
finally
6
finally
7
finally
8
finally
9
finally
finally