Python

Python Exceptions Explained for Beginners (10 Common Error Examples)

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:

  1. Your code runs normally
  2. Something unexpected happens (like dividing by zero)
  3. Python creates an exception object with details about the problem
  4. Python stops executing and displays the error message
  5. 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:

Python

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

Python – Will Crash

# This will crash because we’re dividing by zero
result = 10 / 0

ZeroDivisionError: division by zero

Now let’s catch that error:

Python – Handled Gracefully

try:
result = 10 / 0
except ZeroDivisionError:
print(“You can’t divide by zero!”)
result = 0

print(f”Result: {result}”) # Output: Result: 0

✓ Success: The code runs without crashing. Instead of stopping, it prints a message and continues.
See also  7 Ways to Remove Characters from Strings in Python: Complete Comparison & Performance Guide

Catching Multiple Exception Types

Often your code might raise different exceptions, and you want to handle each one differently:

Python

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:

Python

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:

Python

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)

1. NameError
When it happens: You use a variable that hasn’t been defined

Broken Code:

Python

print(user_name) # user_name hasn’t been defined yet

NameError: name ‘user_name’ is not defined

The Fix:

Python

user_name = “Alice” # Define it first
print(user_name) # Now it works
# Output: Alice

✓ Tip: Common causes: typos in variable names, using a variable before defining it, or forgetting to import a module.

2. TypeError
When it happens: You use the wrong data type for an operation

Broken Code:

Python

age = “25” # This is a string, not a number
result = age + 5 # Can’t add string + number

TypeError: can only concatenate str (not “int”) to str

The Fix:

Python

age = “25”
age = int(age) # Convert to integer first
result = age + 5
print(result) # Output: 30

✓ Tip: Check if you need to convert types. Use int(), str(), float() to convert.

3. ValueError
When it happens: You give a function the right type but wrong value

Broken Code:

Python

age = int(“hello”) # Can’t convert “hello” to an integer

ValueError: invalid literal for int() with base 10: ‘hello’

The Fix:

Python

try:
age = int(“hello”)
except ValueError:
print(“That’s not a valid number!”)
age = 0 # Use a default value

✓ Tip: ValueError usually means you’re trying to convert bad data. Wrap it in try except.

When it happens: You try to access a list index that doesn’t exist

Broken Code:

Python

fruits = [“apple”, “banana”, “orange”]
print(fruits[5]) # Index 5 doesn’t exist (only 0, 1, 2)

IndexError: list index out of range

The Fix (Method 1 – Check Length):

Python

fruits = [“apple”, “banana”, “orange”]
index = 5
if index < len(fruits): print(fruits[index]) else: print("Index out of range!")

See also  Difference between the sep and end parameters in Python print statement

The Fix (Method 2 – Use Try/Except):

Python

fruits = [“apple”, “banana”, “orange”]
try:
print(fruits[5])
except IndexError:
print(“That index doesn’t exist!”)

✓ Tip: Remember Python uses 0-based indexing. A list with 3 items has indices 0, 1, 2.

5. KeyError
When it happens: You try to access a dictionary key that doesn’t exist

Broken Code:

Python

person = {“name”: “Alice”, “age”: 25}
print(person[“email”]) # “email” key doesn’t exist

KeyError: ’email’

The Fix (Method 1 – Use .get()):

Python

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):

Python

person = {“name”: “Alice”, “age”: 25}
if “email” in person:
print(person[“email”])
else:
print(“Email not found!”)

✓ Tip: For dictionaries, always use de>.get() or check with de>if key in dict first.

6. ImportError / ModuleNotFoundError
When it happens: You try to import a module that doesn’t exist or isn’t installed

Broken Code:

Python

import numpy_typo # Typo in the module name

ModuleNotFoundError: No module named ‘numpy_typo’

The Fixes:

Bash – Fix 1: Correct the import

# In your code:
import numpy # Correct spelling

# Or in terminal:
pip install numpy # If the module isn’t installed

✓ Checklist:

  • 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)

7. AttributeError
When it happens: An object doesn’t have the attribute/method you’re trying to use

Broken Code:

Python

text = “hello”
text.uppercase() # Strings don’t have .uppercase() method

AttributeError: ‘str’ object has no attribute ‘uppercase’

The Fix:

Python

text = “hello”
print(text.upper()) # Correct method name
# Output: HELLO

✓ Tip: Different object types have different methods. For strings, use de>.upper(), de>.lower(), de>.strip(), etc.

8. ZeroDivisionError
When it happens: You try to divide by zero

Broken Code:

Python

result = 10 / 0 # Can’t divide by zero

ZeroDivisionError: division by zero

The Fix:

Python

divisor = 0
if divisor != 0:
result = 10 / divisor
print(result)
else:
print(“Can’t divide by zero!”)

✓ Tip: Always check that your divisor isn’t zero before dividing, or use try/except.

9. FileNotFoundError
When it happens: You try to open a file that doesn’t exist

Broken Code:

Python

file = open(“data.txt”, “r”) # File doesn’t exist
content = file.read()

FileNotFoundError: [Errno 2] No such file or directory: ‘data.txt’

The Fix:

Python

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()

✓ Tip: Use de>with statements for safer file handling (automatically closes files).

10. SyntaxError
When it happens: Your code has wrong Python syntax (missing colon, bad indentation, etc.)

Broken Code (Missing Colon):

Python

if x > 5 # Missing colon
print(“x is big”)

See also  Exploring Metaclasses in Python

SyntaxError: invalid syntax

The Fix:

Python

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’)
✓ Tip: SyntaxErrors stop your code from running at all. Python will tell you the line number—go check it.

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

  1. Read the error message carefully. It usually tells you exactly what went wrong and on which line.
  2. Find the exception type. Is it NameError? TypeError? KeyError? Match it to our list above.
  3. Look at the line number. Go to that line in your code and see what’s happening there.
  4. Check the traceback. It shows you the chain of function calls that led to the error (bottom line is the actual error).
  5. Print debug info. Use de>print() to check variable values before the error happens.
  6. Try to reproduce it. Understand WHAT input causes the error, then fix that case.
  7. 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