I find myself writing some methods where there is a code path that should never happen. Here is a simplified example:
double Foo(double x) {
int maxInput = 100000;
double castMaxInput = (double)maxInput;
if (x < 0 || x > castMaxInput || double.IsNaN(x)) {
return double.NaN;
}
double r = 0;
for (double boundary = 1; boundary<=castMaxInput; boundary++) {
if (x <= boundary) {
r += boundary * (x + 1 - boundary);
return r;
}
else {
r += boundary;
}
}
// we should never get here.
throw new SomeException();
}
The exception that would make the most sense here is something like
TheAuthorOfThisMethodScrewedUpException()
Because that's what is going on if we reach the end of the for loop. Unfortunately, with the method structured as above, the compiler does not appear to be smart enough to figure out that the code after the for loop should never happen. So you can't just have nothing there, or the compiler will complain that "not all code paths return a value". Yes, I could put in return double.NaN
after the loop in addition to before it. But that would disguise the source of the problem.
My question is – is there an exception that would be appropriate?