views:

67

answers:

2

Hello

Is there any way to have a yield created iterator continue to the next item when an exception occurs inside one of the iterator blocks?

This is currently not working:

        Boolean result;
        while (true)
        {
            try
            {
               result =  enumerator.MoveNext(); //Taken from a yield created enumerable
               if (!result) break;
            }
            catch (Exception ex)
            {
                Console.WriteLine("CATCHED...");
                continue;
            }
        }

Let me know,

Regards,

Albert

+2  A: 

No there is not. The generated code for a C# iterator does not support exceptions being thrown. If an exception is thrown the MoveNext operation will not complete and the next call will replay from the same place from the standpoint of the generated iterator code.

JaredPar
Not quite, an exception thrown by the enumerator will put it in the "enumeration completed" state.
Hans Passant
So there is no way to make it advance one step? There should be.
aattia
@aattia, the MoveNext method is the way to advance one step. The other code prevents this from happening by throwing an exception. An enumerator that throws an exception is fundamentally broken as it's not useable by 99% of IEnumerable uses. There is little value in adding a method that says "if the iterator is already broken, please step anyways".
JaredPar
+1  A: 

Linq to events, aka RX, aka IObservable has explicit support for errors: http://msdn.microsoft.com/en-us/library/dd783449(VS.100).aspx

Check it out at http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html

Rob Fonseca-Ensor