Since too many python operations return ValueError
, how can we differentiate between them?
Example: I expect an iterable to have a single element, and I want to get it
a, = [1, 2]
: ValueError: too many values to unpacka, = []
: ValueError: too few values to unpackHow can I differentiate between those two cases?? eg
try:
a, = lst
except ValueError as e:
if e.too_many_values:
do_this()
else:
do_that()
I realise that in this particular case I could find a work-around using length/indexing, but the point is similar cases come up often, and I want to know if there's a general approach. I also realise I could check the error message for if 'too few' in message
but it seems a bit crude.
The best way to find and handle a ValueError Exception is with a try-except block. Place your statement between the try and except keywords. If an exception occurs during execution, the except clause you coded in will show up.
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError , but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError .
What Causes ValueError. The Python ValueError is raised when the wrong value is assigned to an object. This can happen if the value is invalid for a given operation, or if the value does not exist. For example, if a negative integer is passed to a square root operation, a ValueError is raised.
Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value. Also, the situation should not be described by a more precise exception such as IndexError.
try:
raise ValueError('my error')
except ValueError as e:
# use str(), not repr(), see
# https://stackoverflow.com/a/45532289/7919597
x = getattr(e, 'message', str(e))
if 'my error' in x:
print('got my error')
(see also How to get exception message in Python properly)
But this might not be a clean solution after all.
The best thing would be to narrow the scope of your try block so that only one was possible. Or don't depend on exceptions to detect those error cases.
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