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")
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With