
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch TypeError Exception in Python
A TypeError occurs in Python when we perform an operation on an object of an inappropriate type. For example, adding a string to an integer or calling a non-callable object. In this article, you will learn how to catch and handle TypeError exceptions using different methods in Python.
TypeError is raised when you use the wrong data type in an operation. You can handle this exception using try-except blocks to prevent the program from crashing and help you correct input. Always test your code where type mismatches are possible, especially when working with user input or dynamic data.
There are several common ways to catch a TypeError in Python -
- Using a try-except block
- Using try-except with an else block
- Handling multiple operations inside a try block
Using try-except Block
The simplest way to catch a TypeError is by placing the risky code inside a try block and catching the exception with an except block.
Example
In this example, we add a string and an integer together, which causes a TypeError -
try: result = "Hello" + 10 except TypeError: print("TypeError caught: Cannot add string and integer.")
We get the output as shown below -
TypeError caught: Cannot add string and integer.
Using try-except with an else Block
You can also use an else block after the except to run code only if no exception occurs. This helps in the clean separation of logic.
Example
In the following example, we check if an operation runs correctly. If not, the TypeError is caught -
try: number = 5 result = number + 3 except TypeError: print("TypeError occurred.") else: print("Operation successful. Result =", result)
Following is the output obtained -
Operation successful. Result = 8
Handling Multiple Operations Inside try Block
Sometimes, you may want to perform several operations that might raise a TypeError. You can wrap them all in a try block and catch the error once.
Example
Here, we perform a multiplication and a function call. The second line causes a TypeError -
try: result = 3 * 4 func = 5 func() # Trying to call an integer except TypeError as e: print("TypeError caught:", e)
The error obtained is as shown below -
TypeError caught: 'int' object is not callable
When Does TypeError Occur
Some common situations where TypeError occurs are as follows -
- Adding incompatible types (e.g., str + int)
- Calling a non-function (e.g., 5())
- Using the wrong number of arguments in a function call
- Using unsupported operations between types (e.g., list + int)