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?
Personally, I do include custom exceptions like that. It's like the condom argument: it's better to have it and not need it than to need it and not have it. If in the rare case that it does occur, including the custom exception message will make tracking down the logic error that much easier, yet your executable is only a tiny bit bigger. Otherwise, your ArgumentOutOfRangeException could happen anywhere. The time it takes you to add the exception far outweighs the time it takes you to track down the error without it.