1
votes

Why c# compiler is not smart enough in the following scenario?

    void ThrowEx() {
        throw new Exception();
    }

    int Test() {
        ThrowEx();
    }

...Test()': not all code paths return a value

Edit: in practice, i want to extract exception throwing logic into a separate method because i'm tired typing stuff like throw new FaultException<MyCustomFault>(new MyCustomFault(), "cannot validate the input");

4
How much analysis do you want the compiler to do? How deep should it go? - John Saunders
Why would you want this? - Doggett
The simple answer is that it's a compiler not an interpreter - ChrisF
I don't see anything wrong with it. By programming language semantic, the method should return an int value. - Madhur Ahuja
This would be the first time that I've ever encountered someone trying to use generic exceptions. Why are you doing that instead of hoisting a concrete class (so you can catch MyCustomFaultExceptions)? - 48klocs

4 Answers

3
votes

It doesn't look between methods; not least, the method could be in a different assembly and could change without rebuilds, or could be virtual, extern, abstract or partial - it would be confusing to spot only a small number of cases.

You could have the ThrowEx return "int", and then:

return ThrowEx();

which would make the compiler happy. Or use generics:

static T ThrowEx<T>() {...}
...
return ThrowEx<int>();
2
votes

ThrowEx() is void. The compiler knows this, and it determines that there is no return value for the Test() method. The compiler is designed to test your successful method production. Injecting a thrown exception as a valid response is not a reasonable compiler expectation.

1
votes

And how do you wish the compiler to handle cases such as

void ThrowEx() { 
    decimal i = ... get 1 from app config;
    decimal div = ... get 0 from app confid
    decimal randomNumber = i / div;
    do some other stuff....
} 

int Test() { 
    ThrowEx(); 
}
0
votes

Among other things, the Debugger or Profiler API could allow throwing the exception in ThrowEx to be skipped, at which point the behavior of Test would be undefined.