TypeError Exception in Python

Handle Type Error exceptions in Python using the try-except block.

TypeError Exception in Python
Type Error in Python

The TypeError Exception in Python is raised when you try to apply any operation or function call to an inappropriate type of object.

For example -

  1. Trying to concatenate a list and a number
  2. Calling a variable as a function
  3. Passing an argument to a function of the wrong type etc.

Example 1

Code/Output

# concatenating list with an integer
x = [1, 2, 3]
y = 2

print(x+y)
>>> TypeError: can only concatenate list (not "int") to list

# passing an unsupported index
x = [1, 2, 3]
print(x[0.5])
>>> TypeError: list indices must be integers or slices, not float

# calling a variable as a function
x = "Pylenin"
x()
>>> TypeError: 'str' object is not callable

# Passing wrong argument
def addition(x, y):
    return x+y

print(addition(10, [1, 2]))
>>> TypeError: unsupported operand type(s) for +: 'int' and 'list'

You can handle these errors using the TypeError Exception class.


Example 2

Code

# concatenating list with an integer
x = [1, 2, 3]
y = 2
try:
    print(x+y)
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")

# passing an unsupported index
x = [1, 2, 3]
try:
    print(x[0.5])
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")


# calling a variable as a function
x = "Pylenin"
try:
    x()
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")


# Passing wrong argument
def addition(x, y):
    return x+y

try:
    print(addition(10, [1, 2]))
except TypeError as e:
    print(f"TypeError handled."
          f"Error reason - {e}")

Output

TypeError handled.Error reason - can only concatenate list (not "int") to list
TypeError handled.Error reason - list indices must be integers or slices, not float
TypeError handled.Error reason - 'str' object is not callable
TypeError handled.Error reason - unsupported operand type(s) for +: 'int' and 'list'

Check out other Python Built-in Exception classes in Python.

built-in-exception-classes - Pylenin
A programmer who aims to democratize education in the programming world and help his peers achieve the career of their dreams.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe