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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With