1

I have some computational functions for configurations for software that will drive a hardware setup. In some cases, the user may input invalid configuration values. I handle this by throwing an exception if invalid values are used, or simply returning my calculated value if the configuration works:

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

Is it considered bad practice to do it this way? Do I always need to have some valid return value if there is a return value to begin with? I'm trying to learn how best to write Pythonic code while still satisfying the needs of my computational methods.

bearplane
  • 700
  • 1
  • 9
  • 22

2 Answers2

8

The purpose of raising an exception is to provide an alternate exit point in the event where a valid return value can't be found. You are using exceptions exactly as they are intended.

However, I would probably check if exhale_dir is non-positive first, which would save you from performing a calculation with an invalid value.

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for your insight. This answers my specific question more completely than the posted duplicate answer. – bearplane Aug 31 '18 at 14:44
2

No. Exceptions are either handled in a piece of code, or thrown, and leave it to the caller to decide what to do with them. If you return something, you have to choose the first option. You chose the second. Makes perfect sense. That's the whole idea of throwing an exception

blue_note
  • 27,712
  • 9
  • 72
  • 90