Hi.
I have a class with an API that allows me to ask for objects until it throws an IndexOutOfBoundsException
.
I want to wrap it into an iterator, to be able to write cleaner code. However, I need to catch the exception to stop iterating:
static IEnumerable<object> Iterator( ExAPI api ) {
try {
for( int i = 0; true; ++i ) {
yield return api[i]; // will throw eventually
}
}
catch( IndexOutOfBoundsException ) {
// expected: end of iteration.
}
}
But...
When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, see Exception Handling Statements (C# Reference).Statements (C# Reference). (from the msdn)
How can I still wrap this api?