Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# compiler flaw?: Not detecting methods that always throw exceptions

Why does the MS C# compiler complain that "not all code paths return 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!

like image 810
Chris Avatar asked Aug 14 '10 13:08

Chris


2 Answers

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.

like image 89
devoured elysium Avatar answered Oct 30 '22 21:10

devoured elysium


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.

like image 26
thelost Avatar answered Oct 30 '22 19:10

thelost