我遇到了一个很奇怪的问题。以下代码不能运行。yield return and try-catch。(C#)
static IEnumerable<int> YieldFun()
{
int[] numbers = new int[3] { 1, 2, 3 };
if(numbers.Count()==3)
throw new Exception("Test...");
//This code continues even an exception was thrown above.
foreach(int i in numbers)
{
if(i%2==1)
yield return numbers[i];
}
}
static void Main(string[] args)
{
IEnumerable<int> result = null;
try
{
result = YieldFun();
}
catch (System.Exception ex) //Cannot catch the exception
{
Console.WriteLine(ex.Message);
}
foreach (int i in result)
{
Console.Write(" " + i);
}
}
两个问题。 首先,即使抛出异常,YieldFun似乎仍能继续工作。 其次,调用者的try-catch块无法捕获抛出的异常。
这是为什么?以及如何解决这个问题?