gpt4 book ai didi

c# - 继续使用 catch block 中设置的值的不良做法?

转载 作者:行者123 更新时间:2023-11-30 20:23:25 28 4
gpt4 key购买 nike

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

//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();
}

编辑

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

关于c# - 继续使用 catch block 中设置的值的不良做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28968236/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com