0

I know that we can not use yield in a try-catch block according to the documentation:

A yield return statement can't be located in a try-catch block. A yield return statement can be located in the try block of a try-finally statement. A yield break statement can be located in a try block or a catch block but not a finally block.

I also know that Python has the same limitation.

My question is: Why?

Why does this result in a compiler error? Is there some sort of underlying reason why this isn't allowed?

Community
  • 1
  • 1

1 Answers1

2

When you use yield, the compiler generates an entire class to handle the requirement of the Iterator pattern.

When you look at what is generated, you will see that the compiler wraps calls to the MoveNext() and Current methods in the generated class in a try..finally block. The requirement is no doubt because of the try..finally spaghetti that will result, possibly preventing Dispose() being called on the generated class.. which would be a problem worth avoiding. It would definitely add complexities into the compiler for guaranteeing certain conditions such as the above one.

Thanks to Chris (in the comments to this post) who shared Eric Lippert's blog post on this exact issue: http://blogs.msdn.com/b/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx

Pretty much what I figured.. but explained much better than I did :)

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • 2
    And here is the official answer: [http://blogs.msdn.com/b/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx](http://blogs.msdn.com/b/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx) - Quick summary (I still recommend reading): you can't return from a finally block, so the compiler can't even generate legal code for this to work. – Christopher Currens Sep 16 '13 at 04:09
  • @ChristopherCurrens Pretty much what I figured.. but, as always, Eric's article has fantastic examples. – Simon Whitehead Sep 16 '13 at 04:12