Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: correct Exception to raise [closed]

In Python, if a set of if and elif conditions are not satisfied, the else statement is reached and executed.

How, and raise which exception type, should a developer notify that such point in the code should not be reached?

Example:

if condition1:
    # do something
elif condition2:
    # do something
else:
    raise ShouldVeNeverGotHereException

This is to ensure that at least one of the above if conditions actually evaluates to True. If there is a pattern more elegant to achieve what I describe, please suggest.

like image 341
Joseph Victor Zammit Avatar asked Jul 26 '26 23:07

Joseph Victor Zammit


1 Answers

You should never write code that can result in loose ends. But assuming you must, probably the best type of Exception to raise is a ValueError.

>>> foo = 3
>>> if foo == 1:
    pass
elif foo == 2:
    pass
else:
    raise ValueError('foo is unexpected value: %s' % foo)


Traceback (most recent call last):
  File "<pyshell#41>", line 6, in <module>
    raise ValueError('foo is unexpected value: %s' % foo)
ValueError: foo is unexpected value: 3
like image 173
Inbar Rose Avatar answered Jul 28 '26 13:07

Inbar Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!