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 Exception Handling
Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
7 min read
Handling NameError Exception in Python
Prerequisites: Python Exception Handling There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are : 1. Misspelled built-in functio
2 min read
Handling OSError exception in Python
Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as "file not found" or "disk full". Below
2 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they
3 min read
Handling EOFError Exception in Python
In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example: [GFGTABS] Python n
4 min read
How To Fix Valueerror Exceptions In Python
Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Pyth
4 min read
Exception Handling Of Python Requests Module
Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the r
4 min read
How to handle KeyError Exception in Python
In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
3 min read
How to log a Python exception?
To log an exception in Python we can use a logging module and through that, we can log the error. The logging module provides a set of functions for simple logging and the following purposes DEBUGINFOWARNINGERRORCRITICALLog a Python Exception Examples Example 1:Logging an exception in Python with an
2 min read
Handling a thread's exception in the caller thread in Python
Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception hand
3 min read