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.
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()
Because you want to keep the Stream open for the duration of the enumeration AND deal with exceptions AND properly close the file handle either way, I don't think you can use a regular enumeration shortcut (the iterator block, yield-return/yield-break).
Instead, just do what the compiler would have done for you and add some:
By implementing IEnumerator yourself, you can also add IDisposable
I didn't test this, but I think it's close.
used like this:
EDIT: I had totally forgotten to add the try-catch block placements. Oops.