C#编译器缺陷?:不检测总是抛出异常的方法

Chr*_*ris 6 c# compiler-construction

为什么MS C#编译器在以下场景中抱怨"并非所有代码路径都返回值"?

public int Foo(bool flag)
{
    if(flag)
    {
        return 1;
    }
    else
    {
        ThrowException(); // this method always throws an exception

        // return -1; // why do I need to add this code that will never be called?
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

dev*_*ium 8

它无法猜测ThrowException()是一个总是抛出异常的方法.为此,您需要静态代码分析.

VS 2010中提供了静态代码分析,但我认为仅适用于更昂贵的VS版本.

  • 绝对正确.但是为了澄清OP点,如果你改变方法ThrowException()来返回一个Exception并将代码更改为:throw ThrowException(),它的行为就像OP想要的那样. (5认同)