Chris
Chris

Reputation: 3712

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?
    }
}

Upvotes: 5

Views: 555

Answers (3)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

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.

Upvotes: 0

thelost
thelost

Reputation: 6694

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.

Upvotes: 1

devoured elysium
devoured elysium

Reputation: 105057

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.

Upvotes: 8

Related Questions