在C#中循环尝试/捕获

时间:2017-04-08 14:48:18

标签: c# try-catch try-catch-finally

try/catch/finallyfor循环中有foreach个阻止。

如果break块中有try语句会怎样?

finally阻止执行吗?

4 个答案:

答案 0 :(得分:2)

是的,即使您有break等跳转声明,最后也会遇到障碍。

  

通常,当控件离开时,finally块的语句会运行   try语句。控制权的转移可以由于正常执行,执行break,continue,goto或return语句,或者从try语句中传播异常而发生。

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

答案 1 :(得分:1)

会的。您可以尝试运行以下示例

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

答案 2 :(得分:1)

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

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

输出:终于到达

答案 3 :(得分:1)

是的,它会点击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