Try/Catch 在 C# 中的循环内

Try/Catch within loop in C#

forforeach 循环中有一个 try/catch/finally 块。

如果 try 块中有 break 语句会发生什么情况?

finally块会被执行吗?

是的,即使你有 break.

这样的跳转语句,finally blocks hit

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.

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

会的。你可以试试运行下面的例子

    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();
    }

是的,它会被击中。这是您可以尝试的示例代码。

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

输出:终于达到了

是的,它会命中 finallyTry Me. 下面将证实我的回答:

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

输出:

0
finally
1
finally
2
finally
3
finally
4
finally
5
finally
6
finally
7
finally
8
finally
9
finally
finally