Search code examples
pythonexceptionraise

What exception to raise for testcase: string length > value? - Python


I am doing some testing, in which I have some Raise in some cases like:

@staticmethod
def concat_strings(string1, string2):
    if type(string1) is not str or type (string2) is not str:
        raise TypeError
    return string1 + string2

@staticmethod
def concat_3strings(string1, string2, string3):
    if type(string1) is not str or type(string2) is not str or type(string3) is not str:
        raise TypeError
    return string1+string2+string3

Now, if I want to check that the length of the strings is 10 at max, would that be "attribute error", or what kind of raise should I do? Why that one?

For example:

    @staticmethod
    def concat_2strings_tam(string1, string2):
        if len(string1)>10 or len(string2)>10:
            raise AttributeError
        return string1+string2

Solution

  • From the python docs:

    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.

    So it sounds like you want ValueError, unless you want to define your own custom exception class.