Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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") 
like image 414
Gary Avatar asked Feb 14 '15 10:02

Gary


People also ask

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.

Is ValueError an exception?

The ValueError exception in Python is raised when the method receives the argument of the correct data type but an inappropriate value. The associated value is a string giving details about the data type mismatch.

What is the significance of using raise ValueError exception block?

When we use the raise keyword, it's not necessary to provide an exception class along with it. When we don't provide any exception class name with the raise keyword, it reraises the exception that last occured. This is used generally inside an except code block to reraise an exception which is catched.


1 Answers

As Gary 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.

like image 100
nijoakim Avatar answered Sep 20 '22 20:09

nijoakim