Handling TypeError Exception in Python (original) (raw)

In Python, a TypeError occurs when an operation or function is applied to an object of an inappropriate type, such as adding a string and an integer. Although Python is dynamically typed, it still expects compatible data types for operations like arithmetic, indexing, iteration and function calls.

Common scenarios that cause TypeError

1. Unsupported Operation Between Two Types

Using arithmetic operations between incompatible types raises a TypeError. For example, combining a string and an integer using the + operator is invalid.

Python `

a = "Geeks" b = 4 print(a + b + a)

`

**Output

TypeError: must be str, not int

To fix this error, convert the number to a string before adding.

Python `

a = "Geeks" b = 4 print(a + str(b) + a)

`

**2. Calling a non-callable Identifier

Trying to use a variable like a string or number as if it were a function will raise a TypeError.

Python `

a = "GeeksforGeeks" print(a())

`

**Output:

TypeError: 'str' object is not callable

To fix this error, just print the variable without parentheses.

Python `

a = "GeeksforGeeks" print(a)

`

**3. Incorrect type of List Index

Python list indices must be integers or slices. Using a string or float as an index will raise a TypeError.

Python `

a = ["geek", "GeeksforGeeks", "geeky", "geekgod"] b = "1" print(a[b])

`

**Output

TypeError: list indices must be integers or slices, not str

To fix this error, convert the string "1" to an integer using int().

Python `

a = ["geek", "GeeksforGeeks", "geeky", "geekgod"] b = "1" print(a[int(b)])

`

**4. Iterating Through a non-iterative Identifier

Objects like integers and floats are not iterable. Trying to use them in a loop will cause a TypeError.

Python `

for a in 1234.567890: print(a)

`

**Output :

TypeError: 'float' object is not iterable

To fix this error, convert the float to a string first, which is iterable.

Python `

for a in str(1234.567890): print(a)

`

Output

1 2 3 4 . 5 6 7 8 9

**5. Passing an Argument of the Wrong Type to a Function

When a function expects numeric types and receives a string or other incompatible type, a TypeError is raised.

Python `

def sub(a, b): print(a - b) sub('a', 1)

`

**Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in
sub('a', 1)
~~~^^^^^^^^
File "/home/guest/sandbox/Solution.py", line 2, in sub
print(a - b)
~~^~~
TypeError: unsupported operand type(s) for -: 'str' and 'int'

To fix this error, pass two numbers to the function instead of a string and a number.

Python `

def sub(a, b): print(a - b) sub(10, 5)

`

Handling TypeError with try-except Block

Sometimes, even if your logic is correct, data from external sources like user input or APIs can cause unexpected TypeErrors. That's where try-except blocks help! They catch the error and let your program continue running gracefully.

Python `

a = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"] b = [0, 1, "2", 3] # Note: "2" is a string, not an integer

for i in range(len(b)): try: print(a[b[i]]) # This will fail when b[i] is a string except TypeError: print("TypeError: Check list of indices")

`

Output

Geeky GeeksforGeeks TypeError: Check list of indices Geek

**Explanation: when "2" (a string) is used as a list index, Python raises a TypeError. But since we’ve wrapped it in a try-except block, the program doesn’t crash.

Best Practices to Avoid TypeError

Avoiding TypeErrorsis better than just catching them. Here are some smart practices to help you:

1. Use isinstance() to check data types before performing operations

if isinstance(a, int) and isinstance(b, int):
print(a + b)

2. Use **type hints in functions to make expected types clear

def multiply(a: int, b: int) -> int:
return a * b

**3. Validate user input: Always check that input is of the expected type especially if it’s coming from forms, files or users.

4. **Don’t overwrite built-in names: Avoid using names like list, str, int, input, etc., for your variables. Doing so can lead to unexpected behavior and confusing errors.