Skip to main content

Cannot yield in the body of a try block with a catch clause

In This Article

CodeRush Classic shows the Cannot yield in the body of a try block with a catch clause code issue if the yield keyword is located within the body of a try block with a catch clause.

#Fix

Move the yield statement out of the try block.

#Purpose

Highlights the yield statements, which would cause the Cannot yield a value in the body of a try block with a catch clause compilation error.

#Example

public IEnumerable GetFileTexts(string files)
{
    string[] fileNames = files.Split(',');
    foreach (string fName in fileNames)
    {
        try
        {
            yield return File.ReadAllText(fName);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
        }
    }
}

Fix:

public IEnumerable GetFileTexts(string files)
{
    string[] fileNames = files.Split(',');
    string text;
    foreach (string fName in fileNames)
    {
        try
        {
            text = File.ReadAllText(fName);
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
            continue;
        }
        yield return text;
    }
}