Подтвердить что ты не робот

Вернуть доход с помощью try catch, как я могу его решить

У меня есть код:

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

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 с вызовом ExceptionMapper в случае catch. Этот метод используется отложенным всеми вызывающими абонентами.

Исключения, которые я должен уловить, исходят из этих вызовов

File.OpenRead()
stream.Read()
4b9b3361

Ответ 1

Поскольку вы хотите, чтобы Stream был открыт на время перечисления И обрабатывать исключения и корректно закрывать дескриптор файла в любом случае, я не думаю, что вы можете использовать регулярный ярлык перечисления (блок итератора, yield-return/выход-пауза).

Вместо этого просто сделайте то, что сделал бы компилятор для вас, и добавьте следующее:

Внедряя IEnumerator самостоятельно, вы также можете добавить IDisposable

public class LazyStream : IEnumerable<string>, IDisposable
{
  LazyEnumerator le;

  public LazyStream(FileInfo file, Encoding encoding)
  {
    le = new LazyEnumerator(file, encoding);
  }

  #region IEnumerable<string> Members
  public IEnumerator<string> GetEnumerator()
  {
    return le;
  }
  #endregion

  #region IEnumerable Members
  System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  {
    return le;
  }
  #endregion

  #region IDisposable Members
  private bool disposed = false;

  public void Dispose()
  {
    Dispose(true);

    GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing)
  {
    if (!this.disposed)
    {
      if (disposing)
      {
        if (le != null) le.Dispose();
      }

      disposed = true;
    }
  }
  #endregion

  class LazyEnumerator : IEnumerator<string>, IDisposable
  {
    StreamReader streamReader;
    const int chunksize = 1024;
    char[] buffer = new char[chunksize];

    string current;

    public LazyEnumerator(FileInfo file, Encoding encoding)
    {
      try
      {
        streamReader = new StreamReader(file.OpenRead(), encoding);
      }
      catch
      {
        // Catch some generator related exception
      }
    }

    #region IEnumerator<string> Members
    public string Current
    {
      get { return current; }
    }
    #endregion

    #region IEnumerator Members
    object System.Collections.IEnumerator.Current
    {
      get { return current; }
    }

    public bool MoveNext()
    {
      try
      {
        if (streamReader.Peek() >= 0)
        {
          int readCount = streamReader.Read(buffer, 0, chunksize);

          current = new string(buffer, 0, readCount);

          return true;
        }
        else
        {
          return false;
        }
      }
      catch
      {
        // Trap some iteration error
      }
    }

    public void Reset()
    {
      throw new NotSupportedException();
    }
    #endregion

    #region IDisposable Members
    private bool disposed = false;

    public void Dispose()
    {
      Dispose(true);

      GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
      if (!this.disposed)
      {
        if (disposing)
        {
          if (streamReader != null) streamReader.Dispose();
        }

        disposed = true;
      }
    }
    #endregion
  }
}

Я не тестировал это, но думаю, что это близко.

используется следующим образом:

using (var fe = new LazyStream(new FileInfo("c:\\data.log"), Encoding.ASCII))
{
  foreach (var chunk in fe)
  {
    Console.WriteLine(chunk);
  }
}

EDIT: я полностью забыл добавить места размещения блоков try-catch. К сожалению.

Ответ 2

Вот фрагмент кода, который работает для меня (я не дошел до условия ошибки).

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;
}

Ответ 3

Изменить - этот ответ на самом деле неверен из-за причин, о которых идет речь в комментариях: "ТОЛЬКО генерация счетчика завернута, но не сама итерация". - но я оставляю этот ответ здесь как пример того, как иногда то, что может показаться работать, не связано с тонкостями языка.

Считай это предостерегающим рассказом - спасибо спасибо. =)


Здесь опция - отделите свой метод на два метода: один открытый и один закрытый. Открытый метод - это оболочка (с try/catch) вокруг вызова частного метода, который является вашим генератором. Например:

public IEnumerable<string> YourFunction(...)
{
    try
    {
        return _yourFunction(...);
    }
    catch (Exception e)
    {
        throw ExceptionMapper.Map(e, file.FullName);
    }
}

private IEnumerable<string> _yourFunction(...)
{
    // Your code here
}

Это позволит вашим пользователям полагаться на генератор, имеющий встроенную обработку исключений. Кроме того, вы можете выполнить большую проверку на своих входах в общедоступном методе, выбрасывая любые исключения по мере необходимости из-за плохих входов и выполняя эти проверки немедленно при вызове метода, а не ожидая, когда будет перечислить перечисляемый первый раз.

Ответ 4

Вы не можете использовать конструкции yield в блоке try/catch. Ограничьте блок try кодом, который может быть брошен, а не все. Если вы не можете этого сделать, вам не повезло - вам нужно поймать его дальше по стеку.

Ответ 5

Взгляните на этот вопрос. Вы можете yield break в исключительном случае yield value после предложения try/catch. Я был обеспокоен производительностью, но там считается, что try не влияет на производительность, в то время как исключения не выбрасываются.

Ответ 6

К сожалению, вы не указали, что именно вы хотите сделать, но можете попробовать просто заставить пользователей функции, которую вы определяете, попробовать/поймать себя:

public IEnumerable<string> YourFunction(...)
{
    //Your code
}

//later:
    //...
    try{
        foreach( string s in YourFunction(file) )
        {
            //Do Work
        }
    }
    catch(Exception e){
        throw ExceptionMapper.Map(e, file.FullName);
    }

Ответ 7

попробуйте этот подход:

public IEnumerable<ReturnData> toto()
{
    using (StreamReader stream = new StreamReader(File.OpenRead(""), Encoding.UTF8))
    {
        char[] buffer = new char[1];
        while (stream.Peek() >= 0)
        {
            ReturnData result;
            try
            {
                int readCount = stream.Read(buffer, 0, 1);
                result = new ReturnData(new string(buffer, 0, readCount));
            }
            catch (Exception exc)
            {
                result = new ReturnData(exc);
            }
            yield return result;
        }
    }
}

public class ReturnData
{
    public string Data { get; private set; }
    public Exception Error { get; private set; }
    public bool HasError { get { return Error != null; } }
    public ReturnData(string data)
    {
        this.Data = data;
    }
    public ReturnData(Exception exc)
    {
        this.Error = exc;
    }
}

Вам просто нужно быть осторожным с таким подходом: вам придется фильтровать исключения на основе серьезности. Некоторые исключения должны остановить весь процесс, другие просто могут быть пропущены и зарегистрированы.

Ответ 8

Другое соображение: если вы используете метод IEnumerable, реализующий yield, который внутренне генерирует исключение, вы не можете поймать эту отдельную ошибку и продолжить перечисление - см. раздел "Обработка исключений" в https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

Пример:

void Main()
{
    // even is okay, odd will cause exception
    var operations = new[] { 2, 16, 5 /* ! */, 8, 91 /* ! */ };

    var results = process(operations);
    var en = results.GetEnumerator();

    "Regular Enumeration".Title();
    testEnumeration(en);

    results = process(operations, ex => log("Handled: {0}", ex.Message));
    en = results.GetEnumerator();   

    "Handled Exceptions".Title();
    testEnumeration(en);

    results = process(operations, ex => log("Handled+: {0}", ex.Message), true);
    en = results.GetEnumerator();   

    "Handled Exceptions and Continue".Title();
    testEnumeration(en);
}

/// run the test and debug results
void testEnumeration(IEnumerator en) {
    int successCount = 0, failCount = 0;
    bool keepGoing = false;
    do {
        try {
            log("==={0}===", "before next");
            keepGoing = en.MoveNext();
            log("==={0}=== (keepGoing={1}, curr={2})", "after next", keepGoing, en.Current);

            // did we have anything?
            if(keepGoing) {
                var curr = en.Current;
                log("==={0}===", "after curr");

                log("We did it? {0}", curr);
                successCount++;
            }
        }
        catch(InvalidOperationException iopex) {
            log(iopex.Message);
            failCount++;
        }
    } while(keepGoing);

    log("Successes={0}, Fails={1}", successCount, failCount);
}

/// enumerable that will stop completely on errors
IEnumerable<int> process(IEnumerable<int> stuff) {
    foreach(var thing in stuff) {
        if(thing % 2 == 1) {
            throw new InvalidOperationException("Aww, you broked it");
        }

        yield return thing;
    }
}
/// enumerable that can yield from exceptions
IEnumerable<int> process(IEnumerable<int> stuff, Action<Exception> handleException, bool yieldOnExceptions = false) {
    bool shouldYield = false;
    foreach(var thing in stuff) {
        var result = thing;
        try {
            if(thing % 2 == 1) {
                throw new InvalidOperationException("Aww, you broked it");
            }

            shouldYield = true;
        }
        catch(Exception ex) {
            handleException(ex);
            // `yield break` to stop loop
            shouldYield = yieldOnExceptions;
            if(yieldOnExceptions) result = -1; // so it returns a different result you could interpret differently
        }
        if(shouldYield) yield return result;
    }
}

void log(string message, params object[] tokens) {
    Console.WriteLine(message, tokens);
}

приводит к

    Regular Enumeration    

--------------------------- 
===before next===
===after next=== (keepGoing=True, curr=2)
===after curr===
We did it? 2
===before next===
===after next=== (keepGoing=True, curr=16)
===after curr===
We did it? 16
===before next===
Aww, you broked it
===before next===
===after next=== (keepGoing=False, curr=16)
Successes=2, Fails=1


    Handled Exceptions    

-------------------------- 
===before next===
===after next=== (keepGoing=True, curr=2)
===after curr===
We did it? 2
===before next===
===after next=== (keepGoing=True, curr=16)
===after curr===
We did it? 16
===before next===
Handled: Aww, you broked it
===after next=== (keepGoing=True, curr=8)
===after curr===
We did it? 8
===before next===
Handled: Aww, you broked it
===after next=== (keepGoing=False, curr=8)
Successes=3, Fails=0


    Handled Exceptions and Continue    

--------------------------------------- 
===before next===
===after next=== (keepGoing=True, curr=2)
===after curr===
We did it? 2
===before next===
===after next=== (keepGoing=True, curr=16)
===after curr===
We did it? 16
===before next===
Handled+: Aww, you broked it
===after next=== (keepGoing=True, curr=-1)
===after curr===
We did it? -1
===before next===
===after next=== (keepGoing=True, curr=8)
===after curr===
We did it? 8
===before next===
Handled+: Aww, you broked it
===after next=== (keepGoing=True, curr=-1)
===after curr===
We did it? -1
===before next===
===after next=== (keepGoing=False, curr=-1)
Successes=5, Fails=0

Обратите внимание, что перечислитель Current "застревает" в последнем успешном MoveNext во время "регулярного перечисления", тогда как обработанные исключения позволяют ему завершить цикл.

Ответ 9

Одна из стратегий заключается в том, что эффективный (если бит messier читать...) состоит в том, чтобы вырвать и обернуть каждый раздел, который может вызвать фактический вызов yield return. Это работает вокруг проблемы, так что сам yield не находится в блоке try/catch, но части, которые могут сбой, все еще содержатся.

Здесь возможна реализация вашего кода:

StreamReader stream = null;
char[] buffer = new char[chunksize];

try
{
    try
    {
        stream = new StreamReader(file.OpenRead(), Encoding);
    }
    catch (Exception ex)
    {
        throw ExceptionMapper.Map(ex, file.FullName);
    }

    int readCount;
    Func<bool> peek = () =>
    {
        try
        {
            return stream.Peek() >= 0;
        }
        catch (Exception ex)
        {
            throw ExceptionMapper.Map(ex, file.FullName);
        }
    };

    while (peek())
    {
        try
        {
            readCount = stream.Read(buffer, 0, chunksize);
        }
        catch (Exception ex)
        {
            throw ExceptionMapper.Map(ex, file.FullName);
        }

        yield return new string(buffer, 0, readCount);
    }
}
finally
{
    if (stream != null)
    {
        stream.Dispose();
        stream = null;
    }
}