0

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?

Flow.NK
  • 368
  • 1
  • 8
  • 17

4 Answers4

2

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.

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

Noel Widmer
  • 4,444
  • 9
  • 45
  • 69
1

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();
    }
Valentin
  • 5,380
  • 2
  • 24
  • 38
1

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

Ranjith V
  • 298
  • 1
  • 3
  • 16
1

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
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64