yield return with try catch, how can i solve it

Khh picture Khh · Feb 21, 2011 · Viewed 33.2k times · Source

I've a piece of code:

using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
    char[] buffer = new char[chunksize];
    while (stream.Peek() >= 0)
    {
       int readCount = stream.Read(buffer, 0, chunksize);

       yield return new string(buffer, 0, readCount);
    }
 }

Now i have to surround this with an try-catch block

try
{
   using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
   {
       char[] buffer = new char[chunksize];
       while (stream.Peek() >= 0)
       {
          int readCount = stream.Read(buffer, 0, chunksize);

          yield return new string(buffer, 0, readCount);
       }
    } 
}
catch (Exception ex)
{
    throw ExceptionMapper.Map(ex, file.FullName)
}

I can't see any way to do what i want.

EDIT The method has the signature

public IEnumerable<string> ReadPieces(int pieces)

I need a try catch with a call to the ExceptionMapper in the catch case. The method is used deferred by all callers.

The exceptions i have to catch are coming from these calls

File.OpenRead()
stream.Read()

Answer

Thomas picture Thomas · Aug 21, 2012

Here is a code snippet, which works for me (I did not reach the error condition).

while (true)
{
    T ret = null;
    try
    {
        if (!enumerator.MoveNext())
        {
            break;
        }
        ret = enumerator.Current;
    }
    catch (Exception ex)
    {
        // handle the exception and end the iteration
        // probably you want it to re-throw it
        break;
    }
    // the yield statement is outside the try catch block
    yield return ret;
}