
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Forcing an Iterator to Stop Iterating
|
351
public class Foo
{
private List<T> _items = new List<T>( );
public IEnumerator GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
if (/*perform some test on the data here*/)
{
// There was a problem with the data, stop.
yield break;
}
else
{
// The data was fine, continue.
yield return (_items[index]);
}
}
}
}
Discussion
It is possible to stop iterations using a throw statement to throw an exception. How-
ever, you cannot place a
catch block within an iterator body to handle the thrown
exception. The
try/catch block must be around the foreach loop as shown here:
Foo test = new Foo( );
// Add elements to the test class...
try
{
foreach ( object o in test) {...}
}
catch (Exception e)
{
// Handle exception from iterator method here...
Console.WriteLine("In outer finally block");
}
When an exception occurs inside the foreach block, the following string will be
displayed:
In outer finally block
For more on how iterators deal with exceptions, see Recipe 6.9.
Another way of terminating an iterator, and thus terminating the
foreach loop, is to
use the
yield break statement. This statement has the same effect as simply exiting
from the function. This
yield break statement can be used only within an iterator
block. This means any method, property ...