#1,193 – yield Statement and try/catch Blocks

The yield return statement is used when defining an iterator to generate the next element within a sequence (IEnumerable).  You cannot include a yield return statement in any of the following places:

  • within a try block that has a catch clause
  • within a catch block
  • within a finally block

You can include a yield return statement within a try block that only has a finally block.

        private static IEnumerable<int> IntsAndTheirDoubles()
        {
            for (int i = 1; i <= 5; i++ )
            {
                yield return i;
                try
                {
                    // Error: Cannot yield a value in the body of a try block
                    //   with a catch clause
                    yield return 2 * i;
                }
                catch (Exception xx)
                {
                    Console.WriteLine("Uh-oh");
                }
            }
        }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,193 – yield Statement and try/catch Blocks

  1. Pingback: Dew Drop – September 30, 2014 (#1866) | Morning Dew

  2. Steven says:

    Good to know. Thanks!

Leave a comment