Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No "unreachable code detected"-warning in Visual Studio for new exception after return

Tags:

c#

i was just wondering why Visual Studio does not show me an "unreachable code detected"-warning for the exception here:

private void ReturnException()
{
    return;
    throw new Exception();
    int iAmUnreachable = 0;
}

The warning appears only for the int. Is there ever any circumstance in which the exception will be thrown?

like image 688
J. Doe Avatar asked Oct 15 '25 18:10

J. Doe


1 Answers

The throw is unreachable but the C# compiler does not produce a warning in the case of a throw statement. This seems strange but it is by design and is documented in this Github issue. It is to maintain backwards compatibility with older compiler versions that did not warn on this (i.e. changing it would generate many harmless warnings). Neal Gafter:

The following types of statements are not reported as unreachable (by design)
- Block statements (however, statements within them may be reported unreachable)
- Throw statements
- Empty statements ;

We do this because that's what the older compiler did and we don't want to "break" existing code. I think these are justified philosophically, but in any case we won't change it.

like image 162
Mike Zboray Avatar answered Oct 17 '25 06:10

Mike Zboray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!