C# compiler flaw?: Not detecting methods that always throw exceptions
Why does the MS C# compiler complain that "not all code paths retu开发者_运维知识库rn a value" in the following scenario?
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?
}
}
Thanks!
It can't guess that ThrowException() is a method that always throws exceptions. For that you'd need static code analysis.
Static code analysis is available in VS 2010, but only for the more expensive versions of VS, I believe.
The else
branch does not have a return
statement. That means that Foo
does not return a value when entering the else
branch.
Why don't you do:
public int Foo(bool flag)
{
if (!flag) {
ThrowException();
}
return 1;
}
BTW I always feel that validation should be done first.
The error message says it all: Not all code path return a value. I reckon the purpose of ThrowException()
is to throw an exception. If it does so, I can see how the error message would seem strange. However, consider the consequence of accepting this a valid code. If the implementation of ThrowException()
was changed at a later point to no longer throw an exception, the code above would suddenly fail, and that would probably come as a big surprise. The compiler is picking the safe road here.
精彩评论