Consider the following code snippet:
int index = FindClosestIndex(frame);
if (_data[index].Frame == frame)
return _data[index];
else
return interpolateData(frame, _data[index - 1], _data[index]);
Now, in this case I have done some checking before this code block to make sure that FindClosestIndex()
will never return 0. It should be impossible. However, the logic in FindClosestIndex
is somewhat complex, so it's very possible that a bug has yet to be discovered in some rare corner case that no one anticipated, and even though my code is correct, FindClosestIndex
may incorrectly return 0.
If it does return 0, I will get an ArgumentOutOfRangeException on the _data[index - 1]
statement. I could let that exception bubble up, but I would rather do this:
if (index == 0)
throw new ApplicationLogicException("There is a bug that caused FindClosestIndex to return an int <= 0 when it shouldn't have.");
Would you recommend this practice of throwing a custom exception if your code detects an error state? What do you do when you have a situation like this?