私は非常に奇妙な問題に遭遇しました。次のコードは予想どおりに実行されません。
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);
}
}
2つの質問。まず、YieldFun は、例外がスローされても引き続き動作するようです。次に、呼び出し元の try-catch ブロックが、スローされた例外をキャッチできません。
なぜこれ?これを解決する方法は?