Some common built-in exceptions in Python

Let’s go through the most common built-in Python exceptions, one by one, with clear examples and step-by-step explanations.

1. SyntaxError

Meaning: Occurs when Python can’t understand your code due to a syntax (grammar) mistake.

Example:

Python

# ❌ Missing colon after if
if 5 > 2
    print("Five is greater than two")    

Output: SyntaxError: expected ':'

Fix:

Python

if 5 > 2:
    print("Five is greater than two")    

2. NameError

Meaning: Happens when you use a variable that hasn’t been defined.

Python

print(age)    

Output: NameError: name 'age' is not defined

Fix:

Python

age = 25
print(age)    

3. TypeError

Meaning: Occurs when you perform an operation on incompatible data types.

Python

# ❌ You can’t add integer and string
result = 10 + "20"    

Fix:

Python

result = 10 + int("20")
print(result)    

4. ValueError

Meaning: Correct type but invalid value.

Python

num = int("abc")    

Fix:

Python

num = int("123")
print(num)    

5. IndexError

Meaning: Accessing an invalid list index.

Python

numbers = [10, 20, 30]
print(numbers[5])    

6. KeyError

Meaning: Accessing a dictionary key that doesn’t exist.

Python

student = {"name": "Ashish", "age": 28}
print(student["grade"])    

7. ZeroDivisionError

Meaning: Dividing a number by zero.

Python

x = 10
y = 0
print(x / y)    

8. FileNotFoundError

Meaning: File does not exist.

Python

file = open("non_existing_file.txt", "r")    

9. ImportError

Meaning: Module cannot be imported.

Python

import mynonexistentmodule    

10. AttributeError

Meaning: Using a method or attribute that doesn’t exist.

Python

text = "Ashish"
text.push("Coder")    

11. IndentationError

Meaning: Incorrect indentation.

Python

def greet():
print("Hello, Ashish!")    

12. MemoryError

Meaning: Python runs out of memory.

Python

x = [1] * (10**10)    

Fixing MemoryError