Why do the following lines of code not create a compiler warning?
void Main() { throw new Exception(); throw new Exception(); }
As I see it, the compiler should inform you that the second throw exception cannot be reached.
Unreachable code is a program code fragment which is never executed. Don't mix it up with dead code which is, unlike unreachable code, a code fragment that can be executed but whose result is never used in any other computation.
After you call throw the method will return immediately and no code following it will be executed.
It is clearly a compiler bug, and it was introduced in C# 3.0 -- right around the time that I heavily refactored the reachability checker. This is probably my bad, sorry.
The bug is completely benign; basically, we just forgot a case in the warning reporter. We generate the reachability information correctly; as others have noted, we correctly trim out the unreachable code before codegen.
The bug is nothing more than a missing case in the warning generator. We have some tricky code in there that ensures that we do not report a zillion warnings when you make some large section of code unreachable. The compiler has code for specifically reporting warnings on unconditional gotos ("goto", "break", "continue"), conditional gotos ("if", "while" and so on), try-catch-finally (which includes forms equivalent to try-catch-finally, like lock and using), blocks, returns (yield return and regular return), local declarations, labelled statements, switches, and expression statements.
Do you see "throw statements" on that list? Me neither. That's because we forgot it.
Apologies for the inconvenience. I'll send a note to QA and we'll get a fix for this into a future version of the language.
Thanks for bringing this to my attention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With