我有一段代码:
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);
}
}
现在我必须用 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)
}
我看不出有什么方法可以做我想做的事。
编辑 该方法有签名
public IEnumerable<string> ReadPieces(int pieces)
我需要一个 try catch
,在 catch
情况下调用 ExceptionMapper
。
该方法由所有调用者延迟使用。
我必须捕获的异常来自这些调用
File.OpenRead()
stream.Read()
最佳答案
这是一个代码片段,对我有用(我没有达到错误条件)。
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;
}
关于c# - yield return with try catch,我该如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067188/