Search code examples
pythontypeerrorexcept

Why do I get a TypeError if I pass only one argument?


def divide(num1,num2):
    try:
        return num1/num2
    except TypeError:
        return "Please provide two integers or floats"
    except ZeroDivisionError:
        return "Please do not divide by zero"

Solution

  • If you don't supply all of the required arguments, the function is never entered, so there's no way to catch that TypeError from inside the function.

    To illustrate, consider a function that immediately errors out:

    >>> def func(a, b, c):
    ...     raise Exception("inside the function")
    ...
    

    Now let's call it with the required arguments:

    >>> func(1, 2, 3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in func
    Exception: inside the function
    

    Here you can see from the traceback (in func) that the function was entered and the error thrown from there. However, if we call it again without the arguments:

    >>> func()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func() takes exactly 3 arguments (0 given)
    

    Note that the traceback doesn't include in func, the error happens before entering the function body. You can only catch it outside the function:

    >>> try:
    ...     func()
    ... except TypeError:
    ...     print('oh no!')
    ...
    oh no!