我在代码中使用了这样的东西:
//some code that gets the group, etc.
Point3d rotationPoint;
try
{
rotationPoint = GetRotationPoint(group) // Throws NoDataFoundException
}
catch(NoDataFoundException)
{
rotationPoint = RequestRotationPoint(); // Let user pick the rotation point instead
}
//...and then simply continue the method
这种方法的原因是我无法检查rotationPoint
是否null
,因为它是struct
。会有其他选择吗?
这是不好的做法,但实际上取决于您使用 Exceptions 来处理系统中的逻辑,而不是重复类似的操作。例外应该是Exceptional
,因为你并没有真正期待它们,所以你会很好地向用户呈现,并尝试继续或优雅地失败。
在这种情况下,您真正想要做的是类似于TryParse
方法:
Point3d rotationPoint;
if(GetRotationPoint(group, out rotationPoint) == false)
{
rotationPoint = RequestRotationPoint();
}
编辑
我应该补充一点,异常是执行此类操作的不良做法的原因是,构造和抛出异常是一项昂贵的操作,可能会导致代码中的性能瓶颈。通常这不是您需要担心的事情,但有时确实如此 - 如果您已经开始沿着这条路进行构建,则可能很难备份。
对于无法控制 GetRotationPoint
API 的情况,这是一种可接受的方法。当您拥有 API 时,将其重组为"字典样式"可以让您完全避免使用异常:
Point3d rotationPoint;
if (!TryGetRotationPoint(group, out rotationPoint)) {
rotationPoint = RequestRotationPoint();
}