for
或foreach
循环中有一个try/catch/finally
块。
如果try
块中有break
语句会发生什么?
finally
块会被执行吗?
是的,即使你有跳跃语句,例如 break
.
通常,当控件离开 尝试语句。由于正常执行、执行中断、继续、转到或返回语句,或者从 try 语句传播异常,可能会发生控制权转移。
从 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");
}
}
输出:终于达到
是的,它会击中finally
.试试我。下面将确认我的答案:
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