收益率和尝试捕获量.(C#)

guo*_*ngj 3 c# yield return try-catch

我遇到了一个非常奇怪的问题.以下代码未预期运行.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

两个问题.首先,即使抛出异常,YieldFun似乎仍然可以继续工作.其次,调用者的try-catch块无法捕获抛出的异常.

为什么这个?以及如何解决这个问题?

Ale*_*kov 6

这是由迭代器的延迟执行引起的.你的异常会比你想象的foreach (int i in result)要晚一些:尝试迭代和抛出,但你不会在那里捕获异常.

在尝试迭代项目之前,不会执行函数体.所以只是调用这个函数实际上并没有达到"throw ..."语句.您可以手动迭代结果以查看抛出异常的确切位置.