- Built-in exception types — the most common exceptions
- SyntaxError — when the code structure is wrong
- TypeError — when an operation is applied to the wrong type
- ValueError — when a function receives the right type but wrong value
- IndexError — when accessing an invalid index
- KeyError — when accessing an invalid dictionary key
- ZeroDivisionError — when dividing by zero
- FileNotFoundError — when a file is not found
- AttributeError — when accessing a non-existent attribute
- NameError — when a variable is not defined
- Exception hierarchy — how exceptions are organized
Understanding Exception Types
Python has many built-in exception types. Each type represents a specific kind of error that can occur in your code. Understanding these types helps you write better error-handling code.
The most common exception types are:
- SyntaxError — invalid syntax
- TypeError — operation on wrong type
- ValueError — right type, wrong value
- IndexError — index out of range
- KeyError — key not found in dictionary
- ZeroDivisionError — division by zero
- FileNotFoundError — file doesn't exist
- AttributeError — attribute not found
- NameError — variable not defined
💡 Key concept: Knowing the type of exception helps you handle it correctly. Each exception type gives you specific information about what went wrong.
Built-in Exceptions Overview
Common Built-in Exceptions
Python provides a wide range of built-in exceptions. Here are the most commonly encountered ones:
# Overview of common exceptions
# 1. SyntaxError — invalid syntax
# print("Hello" # Missing closing parenthesis
# 2. TypeError — wrong type
# "5" + 5 # Can't add string and integer
# 3. ValueError — right type, wrong value
# int("hello") # Can't convert "hello" to integer
# 4. IndexError — index out of range
# [1, 2, 3][5] # Index 5 doesn't exist
# 5. KeyError — key not found
# {"a": 1}["b"] # Key 'b' doesn't exist
# 6. ZeroDivisionError — division by zero
# 10 / 0
# 7. FileNotFoundError — file not found
# open("nonexistent.txt")
# 8. AttributeError — attribute not found
# "string".non_existent_method()
# 9. NameError — variable not defined
# print(undefined_variable)
Characteristics:
- Each exception type has a specific meaning
- They are organized in a hierarchy
- All exceptions inherit from BaseException
- You can catch specific types or all exceptions
Quick Check: What is the base class for all exceptions? (Answer: BaseException)
SyntaxError
Invalid Syntax
A SyntaxError occurs when the Python interpreter encounters code that violates the language's syntax rules. This is the most common error for beginners.
# Common SyntaxError examples
# Missing colon
# if x > 5 # SyntaxError: expected ':'
# Missing closing parenthesis
# print("Hello" # SyntaxError: unexpected EOF
# Missing closing bracket
# my_list = [1, 2, 3 # SyntaxError: expected ']'
# Using a reserved keyword as a variable
# class = "student" # SyntaxError: invalid syntax
# Incorrect indentation
# if True:
# print("Hello") # IndentationError
# Missing operator
# result = 5 3 # SyntaxError: invalid syntax
Characteristics:
- Occurs at compile time
- Cannot be handled with try-except
- Prevents the program from running
- Usually easy to fix
Quick Check: Can SyntaxError be handled with try-except? (Answer: No — it's a compile-time error)
TypeError
Wrong Type
A TypeError occurs when an operation is applied to an object of an inappropriate type. This is one of the most common runtime errors.
# Common TypeError examples
# Adding string and integer
# "5" + 5 # TypeError: can only concatenate str (not "int") to str
# Calling a non-callable object
# my_list = [1, 2, 3]
# my_list() # TypeError: 'list' object is not callable
# Passing wrong number of arguments
# def greet(name):
# return f"Hello, {name}"
# greet() # TypeError: greet() missing 1 required positional argument
# Using an object that doesn't support iteration
# for i in 123: # TypeError: 'int' object is not iterable
# print(i)
# Accessing an index on a non-sequence
# my_dict = {"a": 1, "b": 2}
# my_dict[0] # TypeError: 'dict' object is not subscriptable (when using index)
How to fix:
- Check the data types you're working with
- Use type() to verify types
- Convert types when needed: str(), int(), etc.
- Check function signatures for correct arguments
Quick Check: What causes a TypeError? (Answer: Using the wrong data type for an operation)
ValueError
Right Type, Wrong Value
A ValueError occurs when a function receives the correct type of argument but an inappropriate value. The type is right, but the value doesn't make sense.
# Common ValueError examples
# Converting invalid string to integer
# int("hello") # ValueError: invalid literal for int() with base 10
# Converting invalid string to float
# float("abc") # ValueError: could not convert string to float
# Finding a value that doesn't exist
# my_list = [1, 2, 3]
# my_list.index(5) # ValueError: 5 is not in list
# Removing a value that doesn't exist
# my_list = [1, 2, 3]
# my_list.remove(5) # ValueError: list.remove(x): x not in list
# Using an invalid format specifier
# "{:.2f}".format("string") # ValueError: Unknown format code 'f' for object of type 'str'
How to fix:
- Check the value before using it
- Use try-except to handle invalid values
- Use str.isdigit() to check if a string is numeric
- Check if a value exists before using it
Quick Check: What is the difference between TypeError and ValueError? (Answer: TypeError is wrong type; ValueError is right type but wrong value)
IndexError
Index Out of Range
An IndexError occurs when you try to access an index that doesn't exist in a sequence (list, tuple, string, etc.). The index is either too high or negative beyond the length.
# Common IndexError examples # Accessing an index that doesn't exist # my_list = [1, 2, 3] # print(my_list[5]) # IndexError: list index out of range # Accessing a negative index that's too low # my_list = [1, 2, 3] # print(my_list[-10]) # IndexError: list index out of range # Accessing index in an empty list # empty = [] # print(empty[0]) # IndexError: list index out of range # Accessing index beyond length in a loop # my_list = [1, 2, 3] # for i in range(5): # print(my_list[i]) # IndexError when i == 3
How to fix:
- Check the length using len()
- Use if index < len(list) before accessing
- Use try-except to handle out-of-range errors
- In loops, use range(len(list)) correctly
Quick Check: When does IndexError occur? (Answer: When accessing an index that doesn't exist)
KeyError
Key Not Found in Dictionary
A KeyError occurs when you try to access a dictionary key that doesn't exist. This is a very common error when working with dictionaries.
# Common KeyError examples
# Accessing a non-existent key
# my_dict = {"a": 1, "b": 2, "c": 3}
# print(my_dict["d"]) # KeyError: 'd'
# Using get() to avoid KeyError
# value = my_dict.get("d", "Not found") # Returns "Not found"
# Using in operator to check
# if "d" in my_dict:
# print(my_dict["d"])
# else:
# print("Key not found")
# Accessing nested dictionary key
# user = {"name": "Alice", "address": {"city": "NYC"}}
# print(user["address"]["zip"]) # KeyError: 'zip'
# Accessing a key in a loop
# for key in ["a", "b", "d"]:
# print(my_dict[key]) # KeyError when key is 'd'
How to fix:
- Use dict.get(key, default) for safe access
- Use if key in dict: before accessing
- Use try-except to handle missing keys
- Use defaultdict from collections module
Quick Check: What is the safest way to access a dictionary key? (Answer: Use dict.get(key, default))
ZeroDivisionError
Division by Zero
A ZeroDivisionError occurs when you try to divide a number by zero. This is a mathematical error that can happen in many situations.
# Common ZeroDivisionError examples # Simple division by zero # result = 10 / 0 # ZeroDivisionError: division by zero # Floor division by zero # result = 10 // 0 # ZeroDivisionError: integer division or modulo by zero # Modulo by zero # result = 10 % 0 # ZeroDivisionError: integer division or modulo by zero # In a loop # numbers = [1, 2, 0, 3] # for num in numbers: # result = 10 / num # ZeroDivisionError when num is 0 # Using variables # divisor = 0 # result = 10 / divisor # ZeroDivisionError
How to fix:
- Check if the divisor is 0 before dividing
- Use try-except to handle division by zero
- For lists, filter out zeros before operations
- Use if divisor != 0: before division
Quick Check: What exception is raised when dividing by zero? (Answer: ZeroDivisionError)
FileNotFoundError
File Does Not Exist
A FileNotFoundError occurs when you try to open a file that doesn't exist on the system. This is common when working with file I/O operations.
# Common FileNotFoundError examples
# Opening a non-existent file
# try:
# with open("nonexistent.txt", "r") as file:
# content = file.read()
# except FileNotFoundError:
# print("File not found!")
# Using os.path.exists() to check
# import os
# filename = "nonexistent.txt"
# if os.path.exists(filename):
# with open(filename, "r") as file:
# content = file.read()
# else:
# print(f"File '{filename}' does not exist")
# Using try-except with specific error handling
# try:
# with open("data.txt", "r") as file:
# content = file.read()
# except FileNotFoundError as e:
# print(f"Error: {e}")
How to fix:
- Check if the file exists using os.path.exists()
- Use try-except to handle missing files
- Create the file if it doesn't exist
- Use relative or absolute paths correctly
Quick Check: What exception is raised when opening a non-existent file? (Answer: FileNotFoundError)
AttributeError
Attribute Not Found
An AttributeError occurs when you try to access an attribute or method that doesn't exist for a particular object. This is common when working with objects and modules.
# Common AttributeError examples
# Calling a non-existent method
# my_list = [1, 2, 3]
# my_list.uppercase() # AttributeError: 'list' object has no attribute 'uppercase'
# Accessing a non-existent attribute
# my_str = "hello"
# print(my_str.upper) # AttributeError: 'str' object has no attribute 'upper' (without parentheses)
# Using the wrong method name
# my_dict = {"a": 1, "b": 2}
# my_dict.gets("a") # AttributeError: 'dict' object has no attribute 'gets'
# Accessing an attribute on None
# data = None
# data.append(1) # AttributeError: 'NoneType' object has no attribute 'append'
# Checking if an attribute exists
# if hasattr(my_str, "upper"):
# print(my_str.upper()) # Works
How to fix:
- Check the spelling of methods and attributes
- Use hasattr() to check if an attribute exists
- Use dir() to see available attributes
- Make sure objects are not None
Quick Check: What is the most common cause of AttributeError? (Answer: Using a non-existent method or attribute)
NameError
Variable Not Defined
A NameError occurs when you try to use a variable, function, or module that hasn't been defined yet. This is a very common error for beginners.
# Common NameError examples
# Using a variable before defining it
# print(my_variable) # NameError: name 'my_variable' is not defined
# Misspelling a variable name
# name = "Alice"
# print(nam) # NameError: name 'nam' is not defined
# Using a function before defining it
# greet() # NameError: name 'greet' is not defined
# def greet():
# print("Hello")
# Using an undefined function
# print(len(123)) # NameError: name 'len' is not defined (if len is not imported)
# Using a variable in a different scope
# def my_function():
# x = 10
# print(x) # NameError: name 'x' is not defined
How to fix:
- Check the spelling of variable names
- Make sure variables are defined before use
- Check scope — variables inside functions are not accessible outside
- Import modules before using them
Quick Check: What causes a NameError? (Answer: Using a variable or function that hasn't been defined)
Exception Hierarchy
How Exceptions Are Organized
Python exceptions are organized in a hierarchy. All exceptions inherit from BaseException. Understanding this hierarchy helps you catch exceptions at the right level.
# Exception Hierarchy (simplified)
# BaseException
# ├── SystemExit
# ├── KeyboardInterrupt
# ├── Exception (most exceptions inherit from this)
# │ ├── ArithmeticError
# │ │ ├── ZeroDivisionError
# │ │ ├── OverflowError
# │ │ └── FloatingPointError
# │ ├── AttributeError
# │ ├── EOFError
# │ ├── IndexError
# │ ├── KeyError
# │ ├── NameError
# │ ├── TypeError
# │ ├── ValueError
# │ ├── IOError
# │ │ └── FileNotFoundError
# │ └── StopIteration
# └── GeneratorExit
# Example: Catching multiple exceptions
# try:
# result = 10 / 0
# except ZeroDivisionError:
# print("Cannot divide by zero!")
# except ArithmeticError:
# print("Arithmetic error occurred!")
# except Exception as e:
# print(f"Some other error: {e}")
# Catching Exception catches all exceptions (except system exits)
# try:
# risky_code()
# except Exception as e:
# print(f"An error occurred: {e}")
Key points:
- BaseException — root of all exceptions
- Exception — base class for most exceptions
- More specific exceptions are subclasses
- You can catch specific exceptions or general ones
Quick Check: What is the base class for most exceptions? (Answer: Exception)
Common Mistakes
Things to Watch Out For
Using a Bare Except
# WRONG — catches everything, hides errors
try:
result = 10 / 0
except: # Bare except
print("Something went wrong")
# CORRECT — catch specific exceptions
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Not Reading the Error Message
# WRONG — ignoring the error message # Traceback (most recent call last): # File "", line 1, in # TypeError: 'int' object is not iterable # CORRECT — read and understand the error # The error says you're trying to iterate over an integer # Fix: Use a list or range instead
Handling the Wrong Exception Type
# WRONG — trying to catch the wrong exception
try:
int("hello")
except TypeError: # Wrong — ValueError is raised
print("Type error!")
# CORRECT — catch the correct exception
try:
int("hello")
except ValueError:
print("Value error!")
Quick Check: What is the most common mistake with exception handling? (Answer: Using a bare except or catching the wrong exception type)
Try It Yourself
Experiment with different types of exceptions in the editor below. Modify the code and see what happens.
TYPES OF EXCEPTION PRACTICE
========================================
1. TYPEERROR
TypeError caught: can only concatenate str (not "int") to str
2. VALUEERROR
ValueError caught: invalid literal for int() with base 10: 'hello'
3. INDEXERROR
IndexError caught: list index out of range
4. KEYERROR
KeyError caught: 'c'
5. ZERODIVISIONERROR
ZeroDivisionError caught: division by zero
6. NAMEERROR
NameError caught: name 'undefined_variable' is not defined
7. EXCEPTION HIERARCHY
ZeroDivisionError is a subclass of ArithmeticError
Types of exception practice complete!
You've Got It!
You now understand the different types of exceptions in Python — SyntaxError, TypeError, ValueError, IndexError, KeyError, ZeroDivisionError, FileNotFoundError, AttributeError, NameError, and the exception hierarchy.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the most common exception in Python?
What is the difference between IndexError and KeyError?
Can I create my own exception types?
What is the best practice for exception handling?
What is the exception hierarchy?
What's a common interview question about exception types?
Where to Go From Here
Now that you understand the types of exceptions, check out these related topics:
Exception Handling
Learn how to handle exceptions with try-except.
Learn More →User Defined Exception
Create your own custom exceptions.
Learn More →Logging Exception
Learn how to log exceptions for debugging.
Learn More →