TypeError Exception in Python
By Lenin Mishra
This is the part of the 9th day in the Python 30 series. Check out the series here.
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 concatentate 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.
Related Articles
- Try, Except, Else and Finally in Python
- ZeroDivisionError Exception in Python
- OverflowError Exception in Python
- ArithmeticError Exception in Python
- KeyError Exception in Python
- IndexError Exception in Python
- LookupError Exception in Python
- StopIteration Exception in Python
- NameError Exception in Python
- FileNotFoundError Exception in Python
- Catch Multiple Exceptions in Python