我遇到了一個很奇怪的問題。以下代碼不能運行。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塊無法捕獲拋出的異常。
這是爲什麼?以及如何解決這個問題?