Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between cases of ValueError

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 unpack
  • a, = []: ValueError: too few values to unpack

How 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.

like image 623
blue_note Avatar asked Sep 02 '19 13:09

blue_note


People also ask

How do you check for ValueError?

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.

What is the difference between TypeError and ValueError?

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 a ValueError to occur?

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.

When should you raise ValueError?

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.


1 Answers

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.

like image 111
Joe Avatar answered Oct 26 '22 00:10

Joe