Handling TypeError Exception in Python
Last Updated :
04 Sep, 2023
TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError.
Examples
The general causes for TypeError being raised are:
1. Unsupported Operation Between Two Types
In the following example, the variable 'geek' is a string, and the variable 'num' is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised.
Python3
geek = "Geeks"
num = 4
print(geek + num + geek)
Output :
TypeError: must be str, not int
2. Calling a non-callable Identifier
In the below example code, the variable 'geek' is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised.
Python3
geek = "GeeksforGeeks"
print(geek())
Output :
TypeError: 'str' object is not callable
3. Incorrect type of List Index
In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError.
Python3
geeky_list = ["geek", "GeeksforGeeks", "geeky", "geekgod"]
index = "1"
print(geeky_list[index])
Output :
TypeError: list indices must be integers or slices, not str
4. Iterating Through a non-iterative Identifier
In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError.
Python3
for geek in 1234.567890:
print(geek)
Output :
TypeError: 'float' object is not iterable
5. Passing an Argument of the Wrong Type to a Function
In the below code, subtraction function performs difference operation between two arguments of same type. But while calling the function if we pass arguments of two different type then Type error will be thrown by interpreter.
Python3
def subtraction(num1, num2):
print(num1-num2)
subtraction('a', 1)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
subtraction('a', 1)
File "Solution.py", line 2, in subtraction
print(num1-num2)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Handling TypeError
TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program.
Python3
geeky_list = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"]
indices = [0, 1, "2", 3]
for i in range(len(indices)):
try:
print(geeky_list[indices[i]])
except TypeError:
print("TypeError: Check list of indices")
Output :
Geeky
GeeksforGeeks
TypeError: Check list of indices
Geek
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read