Saturday, 24 August 2013

How to handle "not all code paths return a value" when the logic of the function does ensure a return

How to handle "not all code paths return a value" when the logic of the
function does ensure a return

I suppose the easiest way to explain is by a contrived example:
public static int Fail() {
var b = true;
if (b) {
return 0;
}
}
This code will not compile, and gives the error "not all code paths return
a value," while we humans can clearly see that it does. I DO understand
why. My question is what should be done to remedy the situation. It could
be something like this:
public static int Fail() {
var b = true;
if (b) {
return 0;
}
throw new ApplicationException("This code is unreachable... but here
we are.");
}
But it all just seems rather silly. Is there a better way? Again, this
code is a contrived example (and can be reduced to return 0). My actual
code is massive and complex, but does logically (by mathematical proof)
return a value before trying to exit.

No comments:

Post a Comment