You see an error message and panic. But errors aren’t failures—they’re your code telling you what went wrong. This guide breaks down Python exceptions in simple terms and shows you how to fix 10 of the most common errors you’ll encounter.
Introduction: What Are Exceptions?
When you run Python code and something goes wrong, Python raises an exception. An exception is Python’s way of saying “I found a problem and I’m stopping here unless you tell me how to handle it.”
The key thing to understand: exceptions are not the same as syntax errors.
- Syntax errors stop your code from running at all (Python can’t even parse it)
- Exceptions happen while your code is running, and you can catch and handle them
By the end of this article, you’ll understand:
- What exceptions are and how they work
- How to use try and except to handle errors
- 10 common exceptions and how to fix them
- How to debug when you see an error traceback
What is an Exception?
An exception is an error that occurs while your Python program is running. Python detects the problem and creates an exception object, then stops executing code unless you tell it what to do.
How Exceptions Work
Think of exceptions like this:
- Your code runs normally
- Something unexpected happens (like dividing by zero)
- Python creates an exception object with details about the problem
- Python stops executing and displays the error message
- Your program crashes (unless you catch the exception)
The important part: you can tell Python to catch exceptions and handle them gracefully instead of crashing.
The Try/Except Pattern: How to Handle Exceptions
The most important tool for handling exceptions is the try except block:
try:
# Code that might cause an error
risky_code()
except SomeException:
# Code that runs if that error happens
handle_the_error()
How It Works
Python tries to run the code in the try block. If an exception happens:
- Python stops executing the try block immediately
- It looks for an except block that matches the exception type
- If it finds a match, it runs that except block
- If no match is found, your program crashes
Basic Example: Catching a Simple Error
# This will crash because we’re dividing by zero
result = 10 / 0
Now let’s catch that error:
try:
result = 10 / 0
except ZeroDivisionError:
print(“You can’t divide by zero!”)
result = 0
print(f”Result: {result}”) # Output: Result: 0
Catching Multiple Exception Types
Often your code might raise different exceptions, and you want to handle each one differently:
try:
user_input = input(“Enter a number: “)
number = int(user_input) # Could raise ValueError
result = 10 / number # Could raise ZeroDivisionError
except ValueError:
print(“That’s not a number!”)
except ZeroDivisionError:
print(“You can’t divide by zero!”)
The Else Clause (Optional)
You can add an de>else block that runs only if NO exception occurs:
try:
number = int(“42”)
except ValueError:
print(“That’s not a number!”)
else:
print(f”Success! The number is {number}”)
# Output: Success! The number is 42
The Finally Clause (Optional)
The finally block runs no matter what (whether an exception happened or not). Use it for cleanup:
try:
file = open(“data.txt”, “r”)
content = file.read()
except FileNotFoundError:
print(“File not found!”)
finally:
file.close() # This runs WHETHER OR NOT an error occurred
10 Most Common Python Exceptions (and How to Fix Them)
Broken Code:
print(user_name) # user_name hasn’t been defined yet
The Fix:
user_name = “Alice” # Define it first
print(user_name) # Now it works
# Output: Alice
Broken Code:
age = “25” # This is a string, not a number
result = age + 5 # Can’t add string + number
The Fix:
age = “25”
age = int(age) # Convert to integer first
result = age + 5
print(result) # Output: 30
Broken Code:
age = int(“hello”) # Can’t convert “hello” to an integer
The Fix:
try:
age = int(“hello”)
except ValueError:
print(“That’s not a valid number!”)
age = 0 # Use a default value
Broken Code:
fruits = [“apple”, “banana”, “orange”]
print(fruits[5]) # Index 5 doesn’t exist (only 0, 1, 2)
The Fix (Method 1 – Check Length):
fruits = [“apple”, “banana”, “orange”]
index = 5
if index < len(fruits):
print(fruits[index])
else:
print("Index out of range!")
The Fix (Method 2 – Use Try/Except):
fruits = [“apple”, “banana”, “orange”]
try:
print(fruits[5])
except IndexError:
print(“That index doesn’t exist!”)
Broken Code:
person = {“name”: “Alice”, “age”: 25}
print(person[“email”]) # “email” key doesn’t exist
The Fix (Method 1 – Use .get()):
person = {“name”: “Alice”, “age”: 25}
email = person.get(“email”, “unknown@example.com”)
print(email) # Output: unknown@example.com
The Fix (Method 2 – Check if Key Exists):
person = {“name”: “Alice”, “age”: 25}
if “email” in person:
print(person[“email”])
else:
print(“Email not found!”)
Broken Code:
import numpy_typo # Typo in the module name
The Fixes:
# In your code:
import numpy # Correct spelling
# Or in terminal:
pip install numpy # If the module isn’t installed
- Check spelling of module name
- Install the module if missing: de>pip install module_name
- Make sure you’re using the right Python environment (venv/conda)
Broken Code:
text = “hello”
text.uppercase() # Strings don’t have .uppercase() method
The Fix:
text = “hello”
print(text.upper()) # Correct method name
# Output: HELLO
Broken Code:
result = 10 / 0 # Can’t divide by zero
The Fix:
divisor = 0
if divisor != 0:
result = 10 / divisor
print(result)
else:
print(“Can’t divide by zero!”)
Broken Code:
file = open(“data.txt”, “r”) # File doesn’t exist
content = file.read()
The Fix:
try:
file = open(“data.txt”, “r”)
content = file.read()
except FileNotFoundError:
print(“File not found! Creating a new one…”)
content = “No data”
finally:
if ‘file’ in locals():
file.close()
Broken Code (Missing Colon):
The Fix:
if x > 5: # Added colon
print(“x is big”)
Common SyntaxError Causes:
- Missing colon after de>if, de>for, de>def, etc.
- Wrong indentation
- Mismatched parentheses: de>print(“hello”
- Using wrong quotes: de>print(“text’)
Quick Reference: Common Exceptions at a Glance
| Exception | When It Happens | Quick Fix |
|---|---|---|
| de>NameError | Variable not defined | Define the variable first |
| de>TypeError | Wrong data type used | Convert type with int(), str(), etc. |
| de>ValueError | Right type, wrong value | Validate input, use try/except |
| de>IndexError | List index too high | Check length with len() |
| de>KeyError | Dictionary key doesn’t exist | Use .get() or check with “in” |
| de>ImportError | Module not found | Install with pip, check spelling |
| de>AttributeError | Object has no method | Check correct method name |
| de>ZeroDivisionError | Dividing by zero | Check divisor isn’t zero |
| de>FileNotFoundError | File doesn’t exist | Use try/except, check path |
| de>SyntaxError | Bad Python syntax | Check colons, indentation, quotes |
Exception Handling Checklist: When You See an Error
- Read the error message carefully. It usually tells you exactly what went wrong and on which line.
- Find the exception type. Is it NameError? TypeError? KeyError? Match it to our list above.
- Look at the line number. Go to that line in your code and see what’s happening there.
- Check the traceback. It shows you the chain of function calls that led to the error (bottom line is the actual error).
- Print debug info. Use de>print() to check variable values before the error happens.
- Try to reproduce it. Understand WHAT input causes the error, then fix that case.
- Wrap in try/except if needed. If the error is expected sometimes (like bad user input), catch it gracefully.
Key Takeaways
- Exceptions are errors that happen while your code runs, not syntax problems
- Use de>try/de>except to catch exceptions and handle them gracefully
- Different exceptions have different fixes—read the error message!
- The 10 most common exceptions cover 80% of errors you’ll encounter
- Always validate your inputs and check data types before using them
- Read error messages carefully—they tell you what went wrong and where