检测自身错误的代码?
考虑以下代码片段:
int index = FindClosestIndex(frame);
if (_data[index].Frame == frame)
return _data[index];
else
return interpolateData(frame, _data[index - 1], _data[index]);
现在,在本例中,我在此代码块之前进行了一些检查,以确保 FindClosestIndex()
永远不会返回 0。这应该是不可能的。然而,FindClosestIndex
中的逻辑有些复杂,因此很可能在一些无人预料到的罕见极端情况下尚未发现错误,即使我的代码是正确的,FindClosestIndex
可能会错误地返回 0。
如果它确实返回 0,我将在 _data[index - 1]
语句中收到 ArgumentOutOfRangeException。我可以让该异常冒泡,但我宁愿这样做:
if (index == 0)
throw new ApplicationLogicException("There is a bug that caused FindClosestIndex to return an int <= 0 when it shouldn't have.");
如果您的代码检测到错误状态,您会推荐这种抛出自定义异常的做法吗?当你遇到这样的情况时你会怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我确实包含了类似的自定义异常。这就像安全套的争论:拥有它而不需要它比需要它而不需要它要好。如果在极少数情况下确实发生了,包含自定义异常消息将使追踪逻辑错误变得更加容易,但您的可执行文件只是稍微大一点。否则,您的 ArgumentOutOfRangeException 可能在任何地方发生。添加异常所花费的时间远远超过在没有异常的情况下追踪错误所花费的时间。
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.