1

What type of error should i raise if the the size of some list is not a multiple of some value?

Consider the following code snippet:

def func(x: []):
    if ( len(x) % 2) != 0:
        raise WhatError("?")
    # ...

I have considered TypeError, ValueError and IndexError but I don't think any one of these fit my problem. Are there an errortype for this type of problem or should I just bite the bullet and use one of these?

SørenHN
  • 566
  • 5
  • 20
  • 1
    you could raise a [custom error](https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python), otherwise `ValueError` would be valid – EdChum Sep 21 '18 at 11:03
  • If the documentation specifies that explicitly ("if the size is not divisible by 2 then `ValueError` will be thrown", for example) then it' snot much of a problem. – user202729 Sep 21 '18 at 11:05
  • By the way `len(x)` please. – user202729 Sep 21 '18 at 11:05
  • 2
    `ValueError` is typically used for this kind of thing. – khelwood Sep 21 '18 at 11:07
  • 2
    From [the docs](https://docs.python.org/3/library/exceptions.html#ValueError): "Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError." Seems appropriate. Also remember that you can specify a more detailled cause within the error, e.g. `ValueError("Must be divisible by 2")` – tobias_k Sep 21 '18 at 11:08

2 Answers2

3

From the documentation of ValueError:

exception ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

This seems appropriate in your case. It's also what's commonly used in Python libraries for invalid arguments, e.g. in the math module. Also remember that you can provide a more specific cause within the error, e.g.

raise ValueError("List must have even number of elements")

About your other alternatives: A TypeError seems inappropriate, as the type is correct. An IndexError might have been raised further down the line if the length is not even, but as you do not pass anything that works as an index to the function itself, I would not use that one either.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
3

The number of elements of a list is part of its value, so, among the 3, ValueError is the most appropriate. TypeError would be appropriate if it was not a list/iterable, while IndexError as normally used when trying to access the x[i] element and the list has the wrong size for that.

blue_note
  • 27,712
  • 9
  • 72
  • 90