<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Fabulous Adventures In Coding : exception handling</title><link>http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx</link><description>Tags: exception handling</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>As Timeless As Infinity</title><link>http://blogs.msdn.com/ericlippert/archive/2009/10/15/as-timeless-as-infinity.aspx</link><pubDate>Thu, 15 Oct 2009 13:25:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9904452</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>32</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9904452.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9904452</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt; Recently I found out about a peculiar behaviour concerning division by zero in floating point numbers in C#. It does not throw an exception, as with integer division,&amp;nbsp;but rather returns an "infinity". Why is that?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric:&lt;/STRONG&gt; As I've often said, "why" questions are difficult for me&amp;nbsp;to answer. My first attempt at an answer to a "why" question is usually "because that's what the specification says to do"; this time is no different. The C# specification says to do that in section 4.1.6. But we're only doing that because that's what&amp;nbsp;the IEEE standard for floating point arithmetic says to do. We wish to be compliant with the established industry standard. See &lt;A href="http://en.wikipedia.org/wiki/IEEE_754-1985" mce_href="http://en.wikipedia.org/wiki/IEEE_754-1985"&gt;IEEE standard 754-1985&lt;/A&gt; for details. Most floating point&amp;nbsp;arithmetic&amp;nbsp;is done in hardware these days, and most hardware is compliant with this specification.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;It seems to me that division by zero is a bug no matter how you look at it!&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric:&lt;/STRONG&gt; Well, since clearly that is not how the members of the IEEE standardization committee looked at it in 1985, your statement that it must be a bug "no matter how you look at it" must be incorrect. Some industry experts do not look at it that way.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;Good point. What motivated this design decision?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric:&lt;/STRONG&gt; I wasn't there; I was busy playing&amp;nbsp;Jumpman on my Commodore 64 at the time. But my educated guess is that &lt;STRONG&gt;it is desirable for all possible operations on all floats to produce a well-defined float result&lt;/STRONG&gt;. Mathematicians would call this a "closure" property; that is, the set of floating point numbers is "closed" over all operations.&lt;/P&gt;
&lt;P&gt;Positive infinity seems like a reasonable choice for dividing a positive number by zero. It seems plausible because of course the limit of 1 / x as x goes to zero (from above)&amp;nbsp;is "positive infinity", so why shouldn't 1/0 be the number "positive infinity"?&lt;/P&gt;
&lt;P&gt;Now, speaking &lt;EM&gt;as a mathematician&lt;/EM&gt;, I find that argument specious. A thing&amp;nbsp;and its limit need not have any particular property in common; it is fallacious to reason that just because, say, a sequence has a particular limit that a fact about the limit is also a fact about the sequence. Mathematically, "positive infinity" (in the sense of a limit of a real-valued function; let's leave transfinite ordinals, hyperbolic geometry, and all of that&amp;nbsp;other stuff out of this discussion)&amp;nbsp;is not a number at all and should not be treated as one; rather, it's a terse way of saying "the limit does not exist because the sequence diverges upwards". &lt;/P&gt;
&lt;P&gt;When we divide by zero, essentially what we are saying is "solve the equation x * 0 = 1"; the solution to that equation is not "positive infinity", it is "I cannot because there is no solution to that equation". It's just the same as asking to solve the equation "x + 1 = x" -- saying "x is positive infinity" is not a solution; there is no solution.&lt;/P&gt;
&lt;P&gt;But speaking &lt;EM&gt;as a practical engineer&lt;/EM&gt; who uses floating point numbers to do an imprecise approximation of ideal arithmetic, this seems like a perfectly reasonable choice. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;But surely it is impossible for the hardware to represent "infinity".&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric:&lt;/STRONG&gt; It certainly is possible. You've got 32 bits in a single-precision float; that's over four billion possible floats. All bit patterns of the form &lt;/P&gt;
&lt;P&gt;?11111111??????????????????????? &lt;/P&gt;
&lt;P&gt;are reserved for "not-a-number" values. That's over sixteen million possible NaN combinations. Two of those sixteen million NaN bit patterns are reserved to mean positive and negative infinity. Positive infinity is the bit pattern 01111111100000000000000000000000 and negative infinity is 11111111100000000000000000000000. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;Do all languages and applications use this convention of division-by-zero-becomes-infinity?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric: &lt;/STRONG&gt;No.&amp;nbsp;For example, C#&amp;nbsp;and JScript do but&amp;nbsp;VBScript does not. VBScript gives an error if you do that.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;Then how do language implementors get the desired behaviour for each language if these semantics are implemented by the hardware?&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric: &lt;/STRONG&gt;There are two basic techniques. First, many chips which implement this standard allow&amp;nbsp;the programmer&amp;nbsp;to make float division by zero an exception rather than an infinity. On the 80x87 chip, for example, you can use bit two of the precision control register to determine whether division by zero returns an infinity or&amp;nbsp;throws a hardware exception. &lt;/P&gt;
&lt;P&gt;Second, if you don't want it to be a hardware exception but do want it to be a software exception, then you can check bit two of the status register after each division;&amp;nbsp;it records whether there was&amp;nbsp;a recent divide-by-zero event. &lt;/P&gt;
&lt;P&gt;The latter strategy is used by VBScript; after we perform a division operation we check to see whether the status register recorded a divide-by-zero operation; if it did, then the VBScript runtime creates a divide-by-zero error and the usual VBScript error management&amp;nbsp;process takes over, same as any other error.&lt;/P&gt;
&lt;P&gt;Similar bits exist for other operations that seem like they might be better treated as exceptions, like numeric overflow.&lt;/P&gt;
&lt;P&gt;The existence of the "hardware exception" bits creates problems for the modern&amp;nbsp;language implementor, because we are now often in a world where code written in multiple languages from multiple vendors is running in the same process. Control bits on hardware are the ultimate "global state", and we all know how irksome it is to have global, public state that random code can stomp on. &lt;/P&gt;
&lt;P&gt;For example: I might be misremembering some details, but I seem to recall that Delphi-authored controls set the "overflows cause exceptions" bit. That is, the Delphi implementors did not use the VBScript strategy of "try it, allow it to succeed, and check to see whether the&amp;nbsp;overflow bit was set in the status register". Rather, they used the "make the hardware throw an exception and then catch the exception" strategy. This is deeply unfortunate.&amp;nbsp;When a VBScript script&amp;nbsp;calls a Delphi-authored control, the control flips the bit to force exceptions but it never "unflips" it. If, later on in the script, the VBScript program does an overflow, then we get an unhandled hardware exception because the bit is still set, even though the Delphi control might be long gone! I fixed that by saving away the state of the control register before calling into a component and restoring it when control returns. That's not ideal, but there's not much else we can do.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;User:&lt;/STRONG&gt;&amp;nbsp;Very enlightening! I will be sure to pass this information along to my coworkers. I would be delighted to see a blog post on this.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Eric: &lt;/STRONG&gt;And here you go!&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9904452" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/VBScript/default.aspx">VBScript</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Floating+Point+Arithmetic/default.aspx">Floating Point Arithmetic</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Dialogue/default.aspx">Dialogue</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx">exception handling</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Delphi/default.aspx">Delphi</category></item><item><title>Iterator Blocks, Part Five: Push vs Pull</title><link>http://blogs.msdn.com/ericlippert/archive/2009/07/23/iterator-blocks-part-five-push-vs-pull.aspx</link><pubDate>Thu, 23 Jul 2009 17:05:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9805752</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>13</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9805752.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9805752</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;A while back &lt;A class="" href="http://blogs.msdn.com/ericlippert/archive/2009/06/26/iterators-at-the-summer-games.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2009/06/26/iterators-at-the-summer-games.aspx"&gt;I posted some commentary I did for the Scripting Summer Games where I noted that there is an isomorphism between "pull" sequences and "push" events.&lt;/A&gt; Normally you think of events as something that "calls you", pushing the event arguments at you. And normally you think of a sequence as something that you "pull from", asking it for the next value until you're done. But you can treat a stream of event firings as being a sequence of event argument objects. And similarly, you could implement a sequence iterator so that it called a method for every object in the collection. &lt;A class="" href="http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx" mce_href="http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx"&gt;Heck, you could implement all of LINQ on this model if you really wanted.&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;The implementation of iterator blocks is clearly on&amp;nbsp;the "pull" paradigm. It didn't have to be. We could have&amp;nbsp;gone with a sort of "inversion of control" approach.&amp;nbsp;"Pull" iterators have to simulate coroutines with a little state machine that knows how to get back to&amp;nbsp;the state where the code left off. But we already have a mechanism for code to "get back to the state where it left off" -- that's what you do every time you call a method!&amp;nbsp;You remember what you were doing, call the method, and then pick up where you left off. We could have done the same thing with iterators. We could say that this:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;void Integers(int length, IObserver&amp;lt;int&amp;gt; observer)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; for (int i = 0; i &amp;lt; length; ++i)&amp;nbsp;yield return i;&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;is a syntactic sugar for&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;void&amp;nbsp;Integers(int length, IObserver&amp;lt;int&amp;gt; observer)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; for (int i = 0; i &amp;lt; length; ++i)&amp;nbsp;observer.Yield(i);&lt;BR&gt;&amp;nbsp; observer.Break();&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;That is, we&amp;nbsp;"raise an event" by calling the observer every time something&amp;nbsp;yields, and raise another event when we're done.&lt;/P&gt;
&lt;P&gt;This would be a much more trivial transformation to&amp;nbsp;make&amp;nbsp;than our current state machine approach, but since most people want sequence iteration on the "pull" model, we do the harder work to make that happen.&lt;/P&gt;
&lt;P&gt;I said this had something to do with exception handling. What's the connection?&lt;/P&gt;
&lt;P&gt;Did you notice something weird about how we handle finally blocks? Consider what happens with the "push model":&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;TextReader&amp;nbsp;reader = File.Open(file);&lt;BR&gt;try&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; blah blah blah yield the lines&lt;BR&gt;}&amp;nbsp;&lt;BR&gt;finally&lt;BR&gt;{&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; reader.Close();&lt;BR&gt;}&lt;BR&gt;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;If something in the "blah blah blah" is realized as a call to observer.Yield(line), what happens if the code consuming the result throws? Easy. It is just a method call like any other. The call stack unwinds, we find the finally, the file gets closed, everything is good.&lt;/P&gt;
&lt;P&gt;Now suppose this is realized as the MoveNext of a "pull" iterator. What happens when the code that is consuming the result throws? If we're consuming the result then we've &lt;EM&gt;returned&lt;/EM&gt; from the call to MoveNext! There is no "try", there is no "finally". And yet usually the finally gets executed anyways! If the code that is consuming the results throws, odds are good that it was in a foreach; when foreach throws, the enumerator is disposed, and when the enumerator is disposed, we figure out which "finallys" were around when we last left MoveNext, and we run a special method that does whatever was in the pending finally blocks.&lt;/P&gt;
&lt;P&gt;&lt;EM&gt;This is pretty weird.&lt;/EM&gt; What's going on here is that for finally blocks, "pull" iterators have the same semantics as "push" iterators. When you yield from a try containing a finally, it looks like the finally is still "on the stack" and runs when the consumer throws.&lt;/P&gt;
&lt;P&gt;So what if the try block has a catch?&lt;/P&gt;
&lt;P&gt;The original designers of C# 2.0 -- and remember, this is long before my time on the team -- had a huge debate over this. A debate which was repeated in miniature when I sent them all an&amp;nbsp;email asking for the justification for this decision. There are three basic positions:&lt;/P&gt;
&lt;P&gt;1) Do not allow yield returns in try blocks at all.&amp;nbsp;(Or blocks that are sugars for try blocks, like using blocks.) Use some other mechanism other than "finally" to express the idea of "this is the code that you run when the caller shuts down the enumeration."&lt;/P&gt;
&lt;P&gt;2) Allow yield returns in all try blocks.&lt;/P&gt;
&lt;P&gt;3) Allow yield returns in try blocks that have finally blocks, but not if they have&amp;nbsp;catch blocks.&lt;/P&gt;
&lt;P&gt;The down sides of (1)&amp;nbsp;are that you have to come up with some syntax for representing the "finally" logic that isn't actually a "finally", and that it becomes more difficult to iterate over stuff that requires cleanup, like iterating over the contents of a file. This makes the feature both confusing and weak; we should avoid this option if at all possible.&lt;/P&gt;
&lt;P&gt;The down side of (2) is that the exception handling behaviour beomes deeply, weirdly inconsistent between finally blocks and catch blocks. If you have a&amp;nbsp;yield in a try block with a finally, and the consumer of the iteration throws, then the finally runs, as though you were on the "push" model. But if you have a yield&amp;nbsp;in a try block with a catch, and the consumer of the iteration throws, then the catch does not run, because its not on the call stack. Users have a reasonable expectation that finally and catch work more or less the same way when an exception happens; that is, that control will be consistently transferred to&amp;nbsp;a matching catch or the finally.&lt;/P&gt;
&lt;P&gt;The down side of (3) is that the rule seems arbitrary and weird -- until you read five unnecessarily prolix blog entries that explain what on earth the design team was thinking.&lt;/P&gt;
&lt;P&gt;Obviously, they picked (3), and now you know why.&lt;/P&gt;
&lt;P&gt;Next time, we'll finish up this series with a look at unsafe code.&amp;nbsp;Now that you know all this stuff, seeing why there's no unsafe code allowed in an iterator block is pretty straightforward by comparison.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9805752" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx">Iterators</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx">exception handling</category></item><item><title>Iterator blocks Part Four: Why no yield in catch?</title><link>http://blogs.msdn.com/ericlippert/archive/2009/07/20/iterator-blocks-part-four-why-no-yield-in-catch.aspx</link><pubDate>Mon, 20 Jul 2009 16:44:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9804035</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>14</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9804035.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9804035</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Now that you know why we disallow yielding in a finally, it’s pretty straightforward to see why we also disallow yielding in a catch. &lt;/P&gt;
&lt;P&gt;First off, we still have the problem that it is illegal to “goto” into the middle of the handler of a try-protected region. The &lt;STRONG&gt;only&lt;/STRONG&gt; way to enter a catch block is via the “non-local goto” that is catching an exception. So once you yielded out of the catch block, the next time MoveNext was called, we’d have no way to get back into the catch block where we left off.&lt;/P&gt;
&lt;P&gt;Second, the exception that was thrown and caught is an intrinsic part of the execution of the catch block because it can be re-thrown using the “empty throw” syntax. We have no way of preserving that state across calls to MoveNext. &lt;/P&gt;
&lt;P&gt;I suppose that we could in theory allow yields inside catch blocks that do not have an “empty throw”. We could turn this:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;try &lt;BR&gt;{ &lt;BR&gt;&amp;nbsp; M(); &lt;BR&gt;}&lt;BR&gt;catch(Exception x)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; yield return x.ToString().Length;&lt;BR&gt;&amp;nbsp; yield return 123;&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;into&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;switch(this.state)&lt;BR&gt;{&lt;BR&gt;case 0: goto LABEL0;&lt;BR&gt;case 1: goto LABEL1;&lt;BR&gt;case 2: goto LABEL2;&lt;BR&gt;}&lt;BR&gt;LABEL0:&lt;BR&gt;try &lt;BR&gt;{ &lt;BR&gt;&amp;nbsp; M();&amp;nbsp;&lt;BR&gt;&amp;nbsp; this.state = 2;&lt;BR&gt;&amp;nbsp; goto LABEL2;&lt;BR&gt;}&lt;BR&gt;catch(Exception x)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; this.x = x;&amp;nbsp; &lt;BR&gt;}&lt;BR&gt;this.current = this.x.ToString().Length;&lt;BR&gt;this.state = 1;&lt;BR&gt;return true;&lt;BR&gt;LABEL1:&lt;BR&gt;this.current = 123;&lt;BR&gt;this.state = 2;&lt;BR&gt;return true;&lt;BR&gt;LABEL2:&lt;BR&gt;return false;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;But frankly, that would be pretty weird. It would feel like a very odd restriction to disallow a fundamental part of the “catch” syntax. &lt;/P&gt;
&lt;P&gt;And really, what’s the usage case that motivates this situation in the first place? Do people really want to try something and then yield a bunch of results if it fails? I suppose you could do something like:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;IEnumerable&amp;lt;string&amp;gt; GetFooStrings(Foo foo)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; try&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return Foo.Bar();&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; catch(InvalidFooException x)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return "";&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;… etc.&lt;BR&gt;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;but there are lots of ways to easily rewrite this so that you don’t have to yield in a catch:&lt;/P&gt;&lt;SPAN class=code&gt;IEnumerable&amp;lt;string&amp;gt; GetFooStrings(Foo foo)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; string result;&lt;BR&gt;&amp;nbsp; try&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; result = Foo.Bar();&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; catch(InvalidFooException x)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; result = "";&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; yield return result;&lt;BR&gt;… etc.&lt;BR&gt;&lt;/SPAN&gt;
&lt;P&gt;Since there are usually easy workarounds, and we would have to put crazy-seeming restrictions on the use of re-throws, it’s easier to simply say “no yields inside a catch”.&lt;/P&gt;
&lt;P&gt;We still haven’t explained why it is &lt;EM&gt;illegal&lt;/EM&gt; to yield inside a try that has a catch, nor why it is &lt;EM&gt;legal&lt;/EM&gt; to yield inside a try that has a finally. To understand why, next time I’ll need to muse about the duality between sequences and events. &lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9804035" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx">Iterators</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx">exception handling</category></item><item><title>Iterator Blocks, Part Three: Why no yield in finally?</title><link>http://blogs.msdn.com/ericlippert/archive/2009/07/16/iterator-blocks-part-three-why-no-yield-in-finally.aspx</link><pubDate>Thu, 16 Jul 2009 16:18:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9798914</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>10</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/9798914.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=9798914</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;There are three scenarios in which code could be executing in a finally in an iterator block. In none of them is it a good idea to yield a value from inside the finally, so this is illegal across the board. The three scenarios are (1) normal cleanup, (2) exception cleanup, and (3) iterator disposal.&lt;/P&gt;
&lt;P&gt;For the first scenario, suppose we have something like&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;try&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; Setup();&lt;BR&gt;&amp;nbsp; yield return M();&lt;BR&gt;}&lt;BR&gt;finally&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; yield return N();&lt;BR&gt;&amp;nbsp; Cleanup();&lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;How should we transform this into an iterator state machine? Naively, we want to do something like:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;switch (this.state)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; case 0: goto LABEL0;&lt;BR&gt;&amp;nbsp; case 1: goto LABEL1:&lt;BR&gt;&amp;nbsp; case 2: goto LABEL2:&lt;BR&gt;&amp;nbsp; case 3: goto LABEL3:&lt;BR&gt;}&lt;BR&gt;LABEL0:&lt;BR&gt;try&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; Setup();&lt;BR&gt;&amp;nbsp; this.current = M();&lt;BR&gt;&amp;nbsp; this.state = 1;&lt;BR&gt;&amp;nbsp; return true; // BUT DON'T RUN THE FINALLY!&lt;BR&gt;LABEL1:&lt;BR&gt;}&lt;BR&gt;finally&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; this.current = N();&lt;BR&gt;&amp;nbsp; this.state = 2;&lt;BR&gt;&amp;nbsp; return true;&lt;BR&gt;LABEL2:&lt;BR&gt;&amp;nbsp; Cleanup();&lt;BR&gt;}&lt;BR&gt;LABEL3:&lt;BR&gt;this.state = 3;&lt;BR&gt;return false;&lt;BR&gt;&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;There's an immediate problem with this: we both "goto" into a finally block and "return" out of one. Neither&amp;nbsp;is legal. &lt;/P&gt;
&lt;P&gt;Leaving a finally block via "return" is illegal because it is weird. Suppose the try block returns, causing the finally to execute. What happens when the finally block returns? The original return value&amp;nbsp;would be&amp;nbsp;lost and some other return value&amp;nbsp;would be&amp;nbsp;substituted for it.&amp;nbsp;This seems bizarre and bug-prone, so its not legal; you cannot exit a finally via return. And of course, you don't want the finally to run after the return in the try in this case!&lt;/P&gt;
&lt;P&gt;Furthermore,&amp;nbsp;in the CLR model of exception handling it is illegal to branch via a goto into a try block or its "handler" (that is, the catch or finally clause). Nor can you branch out of the handler.&amp;nbsp;These special&amp;nbsp;regions have special code that needs to be run when the region is entered and exited; you cannot skip&amp;nbsp;either with a goto. &lt;/P&gt;
&lt;P&gt;So we have no immediately obvious way to generate verifiable code for this scenario. Right off the bat, we have a huge number of points against this feature; we'd have to either convince the CLR guys to allow spaghetti code involving protected regions, or come up with some clever technique for generating this code.&lt;/P&gt;
&lt;P&gt;And that's just the scenario where nothing is going wrong yet! Suppose a miracle happens and we manage to successfully generate code for scenario one. Now consider our second scenario, where M throws exception X. Remember, the finally block "catches" the exception and processes the cleanup code. If the cleanup code throws, then the original exception is discarded and the new processing of the new exception takes over. If the cleanup code succeeds, then the original exception continues to be "thrown" up the call stack, looking for more finally blocks or catch blocks.&lt;/P&gt;
&lt;P&gt;Suppose the cleanup code does not throw. What should the control flow look like? The caller calls MoveNext for the first time. M() throws X. The finally block takes over. The finally block calls N(), and returns control to the caller with the results of N() !? What happened to X, the exception? Is it just waiting there, in limbo? When the second call to MoveNext happens, should the cleanup code get run then, and X suddenly pops back into existence and continues to be thrown up the stack? That makes no sense at all; &lt;STRONG&gt;the two calls to MoveNext could have had completely different stacks&lt;/STRONG&gt;! This is crazy, plus we have no mechanism at all in the CLR for these kind of shenanigans.&lt;/P&gt;
&lt;P&gt;Third, suppose we manage to solve all these problems. Now consider what happens when the caller calls MoveNext, M() succeeds, control returns to the caller, and the caller calls an early Dispose() on the enumerator. (I guess they wanted only one item.) We generate a Dispose method that checks the current state and executes any pending finally blocks. What the heck is the Dispose method supposed to do when it encounters the yield return in the pending finally block? We're not even in a call to MoveNext anymore! Should we call N() and ignore the result? Should we return from the Dispose() after the call to N(), or do the cleanup and then return? What exactly should the control flow do here? We're in a context where &lt;EM&gt;we might not even be iterating anymore, and yet we're still yielding.&lt;/EM&gt;&lt;/P&gt;
&lt;P&gt;It really doesn't make any logical sense to do a yield return in this scenario; we're possibly not in a position where the caller is expecting things to continue to be yielded to it.&lt;/P&gt;
&lt;P&gt;So in short, we'd have to do at least two impossible things in order to enable a scenario that makes no sense in the first place. If ever a feature called out to be cut at the design phase, this is it. Therefore: no yields inside finally blocks. Thank goodness for that.&lt;/P&gt;
&lt;P&gt;Next time: now that you know all that, figuring out "why no yields inside catch blocks" is pretty straightforward.&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9798914" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Language+Design/default.aspx">Language Design</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx">Iterators</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx">exception handling</category></item><item><title>Vexing exceptions</title><link>http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx</link><pubDate>Wed, 10 Sep 2008 22:28:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8941803</guid><dc:creator>Eric Lippert</dc:creator><slash:comments>35</slash:comments><comments>http://blogs.msdn.com/ericlippert/comments/8941803.aspx</comments><wfw:commentRss>http://blogs.msdn.com/ericlippert/commentrss.aspx?PostID=8941803</wfw:commentRss><description>&lt;DIV class=mine&gt;
&lt;P&gt;Writing good error handling code is hard in any language, whether you have exception handling or not. When I'm thinking about what exception handling I need to implement in a given program, I first classify every exception I might catch into one of four buckets which I label &lt;STRONG&gt;fatal&lt;/STRONG&gt;, &lt;STRONG&gt;boneheaded&lt;/STRONG&gt;, &lt;STRONG&gt;vexing&lt;/STRONG&gt; and &lt;STRONG&gt;exogenous&lt;/STRONG&gt;.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Fatal&lt;/STRONG&gt; exceptions are &lt;EM&gt;not your fault&lt;/EM&gt;, you &lt;EM&gt;cannot prevent them&lt;/EM&gt;, and you &lt;EM&gt;cannot sensibly clean up from them&lt;/EM&gt;. They almost always&amp;nbsp;happen because the process is deeply diseased and is about to be put out of its misery. Out of memory, thread aborted, and so on. There is absolutely no point in catching these because nothing your puny user code can do will fix the problem. Just let your "finally" blocks run and hope for the best.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Boneheaded&lt;/STRONG&gt; exceptions are &lt;EM&gt;your own darn fault&lt;/EM&gt;, you &lt;EM&gt;could have prevented them&lt;/EM&gt; and therefore &lt;EM&gt;they are bugs in your code&lt;/EM&gt;. You should not catch them; doing so is hiding a bug in your code. Rather, you should write your code so that the exception cannot possibly happen in the first place, and therefore does not need to be caught. That argument is null, that typecast is bad, that index is out of range, you're trying to divide by zero – these are all problems that you could have prevented very easily in the first place, so prevent the mess in the first place rather than trying to clean it up.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Vexing&lt;/STRONG&gt; exceptions are the result of &lt;EM&gt;unfortunate design decisions&lt;/EM&gt;. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.&lt;/P&gt;
&lt;P&gt;The classic example of a vexing exception is &lt;SPAN class=code&gt;Int32.Parse&lt;/SPAN&gt;, which throws if you give it a string that cannot be parsed as an integer. But the 99% use case for this method is transforming strings input by the user, which could be any old thing, and therefore it is in no way &lt;EM&gt;exceptional&lt;/EM&gt; for the parse to fail. Worse, there is no way for the caller to determine ahead of time whether their argument is bad &lt;EM&gt;without implementing the entire method themselves&lt;/EM&gt;, in which case they wouldn't need to be calling it in the first place.&lt;/P&gt;
&lt;P&gt;This unfortunate design decision was so vexing that of course the frameworks team implemented &lt;SPAN class=code&gt;TryParse&lt;/SPAN&gt; shortly thereafter which does the right thing.&lt;/P&gt;
&lt;P&gt;You have to catch vexing exceptions, but doing so is vexing.&lt;/P&gt;
&lt;P&gt;Try to never write a library yourself that throws a vexing exception.&lt;/P&gt;
&lt;P&gt;And finally, &lt;STRONG&gt;exogenous&lt;/STRONG&gt; exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic. Consider this pseudo-C# code, for example:&lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;try&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; using ( File f = OpenFile(filename, ForReading) )&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Blah blah blah&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;}&lt;BR&gt;catch (FileNotFoundException)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; // Handle filename not found &lt;BR&gt;}&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;Can you eliminate the try-catch?&amp;nbsp; &lt;/P&gt;&lt;SPAN class=code&gt;
&lt;P&gt;if (!FileExists(filename))&lt;BR&gt;&amp;nbsp; // Handle filename not found &lt;BR&gt;else&lt;BR&gt;&amp;nbsp; using ( File f = ...&lt;/P&gt;&lt;/SPAN&gt;
&lt;P&gt;This isn't the same program. There is now a "race condition". Some other process could have deleted, locked, moved or changed the permissions of the file between the FileExists and the OpenFile.&lt;/P&gt;
&lt;P&gt;Can we be more sophisticated? What if we lock the file? That doesn't help. The media might have been removed from the drive, the network might have gone down… &lt;/P&gt;
&lt;P&gt;You’ve got to catch an exogenous exception because it always could happen no matter how hard you try to avoid it; it’s an exogenous condition outside of your control.&lt;/P&gt;
&lt;P&gt;So, to sum up:&lt;/P&gt;
&lt;P&gt;• Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.&lt;BR&gt;• Fix your code so that it never triggers a boneheaded exception –&amp;nbsp;an "index out of range" exception should never happen in production code.&lt;BR&gt;• Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid&amp;nbsp;calling a vexing method,&amp;nbsp;catch&amp;nbsp;its vexing&amp;nbsp;exceptions.&lt;BR&gt;• Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.&lt;BR&gt;&lt;/P&gt;&lt;/DIV&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8941803" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/ericlippert/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/Code+Quality/default.aspx">Code Quality</category><category domain="http://blogs.msdn.com/ericlippert/archive/tags/exception+handling/default.aspx">exception handling</category></item></channel></rss>