c# - yield return with try catch,我该如何解决

标签 c# .net-3.5 try-catch yield-return

我有一段代码:

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/

相关文章:

c# - Yield 方法中的垃圾收集

c# - 从两个不同的位置安装 ClickOnce 应用程序

c# - 为什么这种扩展方法不起作用?

java - 在输入错误值后要求用户再次输入。输入不匹配异常?

c++ try and catch 时的返回值

c# - 当前上下文中不存在名称 'sqlDbType'

c# - 身份服务器在/connect/authorize/callback中继续显示 “Showing login: User is not authenticated”

asp.net-mvc - MVC 2 区域注册路由顺序

swift - 如何在 Swift 中使用 try-catch?

c# - 如何在我的 winfoms(c#) 中使用 ffmpeg.net?