继续使用 catch 块中设置的值的不良做法?

Bad practice to continue with value set in catch block?

我在我的代码中使用了这样的东西:

//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。 会有替代方案吗?

这是一种不好的做法,但实际上是因为您使用异常来处理系统中的逻辑,而不是您在重复类似的操作。例外应该是 Exceptional 因为你并不是真的期待它们,所以你会很好地呈现给用户并尝试继续或优雅地失败。

在这种情况下,您真正​​想要做的是遵循 TryParse 方法:

 Point3d rotationPoint;
 if(GetRotationPoint(group, out rotationPoint) == false)
 {
    rotationPoint = RequestRotationPoint();
 }

编辑

我应该补充一点,异常对于做这类事情来说是不好的做法,原因是构造和抛出异常是一项昂贵的操作,这可能会导致代码出现性能瓶颈。通常这不是你需要担心的事情,但有时它是 - 如果你已经开始沿着这条路建设,可能很难后退。

当您无法控制 GetRotationPoint API 时,这是一种可接受的方法。当您拥有 API 时,将其重组为“dictionary style”将使您完全避免使用异常:

Point3d rotationPoint;
if (!TryGetRotationPoint(group, out rotationPoint)) {
    rotationPoint = RequestRotationPoint(); 
}