Is ValueError a suitable exception to raise if the user passes arguments of different lengths that should be the same?

In the function, I want to make sure that the arguments a and b have the same length. I want to raise an exception for this if I have not complied. I know that ValueError is for an exception where the argument itself does not meet certain criteria. Is ValueError a suitable error to raise in this case, when the criteria are between the arguments? If not, would any standard Python exception be more appropriate?

def func(a, b): if len(a) != len(b): raise ValueError("list a and list b must have the same length") 
+6
source share
1 answer

As Gary notes in the comments, ValueError is the right choice.

Another rival will be IndexError , as suggested by Wikiii122. However, according to Python docs,

exception IndexError

Raised when the sequence index is out of range. (Slice indexes are silently truncated to fall into the valid range; if the index is not a prime integer, TypeError is raised.)

This would probably be triggered if you didn't bother to raise an exception, but not as descriptive as TypeError, whose documentation looks like this:

exception ValueError

Raised when an inline operation or function receives an argument with the correct type but an invalid value , and the situation is not described by a more specific exception, such as IndexError.

+2
source

Source: https://habr.com/ru/post/982484/


All Articles