【问题标题】:Is it bad practice to have a function that doesn't return if it throws an exception? [duplicate]如果函数抛出异常则不返回是不好的做法吗? [复制]
【发布时间】:2018-08-31 14:15:09
【问题描述】:

我有一些用于驱动硬件设置的软件配置的计算功能。在某些情况下,用户可能会输入无效的配置值。如果使用了无效值,我会通过抛出异常来处理此问题,或者如果配置有效,则只需返回我的计算值:

def calc_exhale_dur(breath_rate, inh_dur, breath_hold_dur):
    """Calculate exhalation duration.

    Args:
        breath_rate (float): animal breath rate (br/min)
        inh_dur (float): animal inhalation duration (ms)
        breath_hold_duration (float): animal breath hold duration (ms)
    """

    single_breath_dur = calc_breath_dur(breath_rate)
    exhale_dur = single_breath_dur - (inh_dur + breath_hold_dur)

    if (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur:
        raise error.ConfigurationError
    elif exhale_dur <= 0:
        raise error.ConfigurationError
    else:
        return exhale_dur

这样做是否被认为是不好的做法?如果有一个返回值开始,我是否总是需要有一些有效的返回值?我正在尝试学习如何最好地编写 Pythonic 代码,同时仍然满足我的计算方法的需求。

【问题讨论】:

  • 如果抛出异常,返回的意义何在。 ?

标签: python python-3.x


【解决方案1】:

引发异常的目的是在找不到有效返回值的情况下提供备用退出点。您正在完全按照预期使用异常。

但是,我可能会先检查 exhale_dir 是否为非正数,这样可以避免您执行无效值的计算。

if exhale_dur <= 0:
    raise error.ConfigurationError
elif (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur):
    raise error.ConfigurationError

# You can also omit the else, since the only way to reach this point
# is to *not* have raised an exception. This is a matter of style, though.
return exhale_dur

【讨论】:

  • 感谢您的洞察力。这比发布的重复答案更完整地回答了我的具体问题。
【解决方案2】:

没有。异常要么在一段代码中处理,要么被抛出,并留给调用者来决定如何处理它们。如果您退货,您必须选择第一个选项。你选择了第二个。完全有道理。这就是抛出异常的全部想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多