Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does throwing 2 exceptions in a row not generate an unreachable code warning?

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.

like image 274
DaveShaw Avatar asked Jun 16 '11 12:06

DaveShaw


People also ask

What does unreachable code mean in C#?

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.

Does throw Return C#?

After you call throw the method will return immediately and no code following it will be executed.


1 Answers

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.

like image 52
Eric Lippert Avatar answered Oct 04 '22 23:10

Eric Lippert