Gary
Gary

Reputation: 2007

Is ValueError an appropriate exception to raise if user passes arguments of different lengths, which meant to be the same?

In a function, I want to make sure arguments a and b have the same length. I want to raise an Exception for this if not complied. I know ValueError is for exception where an argument itself doesn't conform some particular criteria. Is ValueError an appropriate error to raise in this case where criteria is between arguments? If not, any standard Python exception more appropriate?

def func(a, b):
    if len(a) != len(b):
        raise ValueError("list a and list b must have the same length")

Upvotes: 30

Views: 18712

Answers (1)

nijoakim
nijoakim

Reputation: 958

As johnrsharpe points out in the comments, ValueError is the appropriate choice.

Another contender would be IndexError, as suggested by Wikiii122. However, according to the Python docs,

exception IndexError

Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not a plain integer, TypeError is raised.)

This is likely what would be raised anyway if you didn't bother to raise an exception, but is not as descriptive as ValueError whose documention is as follows:

exception ValueError

Raised when a built-in 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.

Upvotes: 25

Related Questions