
Python
Learn how Python organizes exceptions and recognize the most common types you'll encounter.
Python organizes exceptions in a tree structure. At the top is `BaseException`, with `Exception` as the most common parent for errors we handle:
# Simplified exception hierarchy
BaseException
āāā Exception
ā āāā ArithmeticError
ā ā āāā ZeroDivisionError
ā ā āāā OverflowError
ā ā āāā FloatingPointError
ā āāā LookupError
ā ā āāā IndexError
ā ā āāā KeyError
ā āāā OSError (FileNotFoundError, etc.)
ā āāā TypeError
ā āāā ValueError
ā āāā AttributeError
ā āāā NameError
ā āāā ... (many more)
āāā KeyboardInterrupt
āāā SystemExit# 1. ZeroDivisionError - cannot divide by zero
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Math error: {e}")
# 2. ValueError - wrong value for data type
try:
number = int("abc") # "abc" cannot convert to int
except ValueError as e:
print(f"Value error: {e}")
# 3. IndexError - list index out of bounds
try:
items = ["a", "b", "c"]
print(items[10]) # Only indices 0, 1, 2 exist
except IndexError as e:
print(f"Index error: {e}")
# 4. KeyError - dictionary key doesn't exist
try:
student = {"name": "Alice", "age": 20}
print(student["email"]) # "email" key not in dict
except KeyError as e:
print(f"Key error: {e}")
# 5. TypeError - wrong data type for operation
try:
result = "5" + 10 # Can't add string and integer
except TypeError as e:
print(f"Type error: {e}")
# 6. AttributeError - object doesn't have attribute
try:
text = "hello"
print(text.upper_case) # No 'upper_case' method
except AttributeError as e:
print(f"Attribute error: {e}")
# 7. NameError - variable doesn't exist
try:
print(undefined_variable)
except NameError as e:
print(f"Name error: {e}")
# 8. FileNotFoundError - file doesn't exist
try:
with open("/nonexistent/file.txt") as f:
content = f.read()
except FileNotFoundError as e:
print(f"File error: {e}")You can catch specific exception types to handle different errors differently:
# Different handling for different errors
def get_user_data(user_id, data_dict):
try:
# Could raise KeyError or TypeError
user = data_dict[user_id]
age = int(user["age"])
return age
except KeyError as e:
print(f"Missing data: {e}")
return None
except TypeError as e:
print(f"Type mismatch: {e}")
return None
except ValueError as e:
print(f"Invalid value: {e}")
return None
# Works fine
users = {1: {"name": "Alice", "age": "25"}}
print(get_user_data(1, users)) # Returns 25
# Handles missing key
print(get_user_data(2, users)) # KeyError handled
# Handles type error
print(get_user_data("wrong", users)) # TypeError handledSome exceptions are related through parent classes. Catching the parent catches all children:
# LookupError is parent of IndexError and KeyError
try:
items = [1, 2, 3]
print(items[10]) # IndexError is a LookupError
except LookupError: # Catches both IndexError AND KeyError
print("Item not found!")
# ArithmeticError is parent of ZeroDivisionError
try:
result = 10 / 0 # ZeroDivisionError is an ArithmeticError
except ArithmeticError:
print("Math error occurred!")
# OSError is parent of FileNotFoundError, PermissionError, etc.
try:
with open("/restricted/file.txt") as f:
content = f.read()
except OSError as e: # Catches file-related errors
print(f"File system error: {e}")| Exception | Cause | Example |
|---|---|---|
| `ZeroDivisionError` | Division by zero | `10 / 0` |
| `ValueError` | Wrong value for type | `int("abc")` |
| `IndexError` | List index out of range | `[1,2][5]` |
| `KeyError` | Dict key doesn't exist | `{}["missing"]` |
| `TypeError` | Wrong data type | `"text" + 5` |
| `AttributeError` | Attribute doesn't exist | `"text".missing_method()` |
| `NameError` | Variable doesn't exist | `undefined_var` |
| `FileNotFoundError` | File doesn't exist | `open("missing.txt")` |
| `ImportError` | Module can't import | `import nonexistent` |
| `RuntimeError` | General runtime error | Various scenarios |
# Checking exception relationships
exceptions = [
ValueError,
IndexError,
KeyError,
ZeroDivisionError,
FileNotFoundError
]
print("Exception hierarchies:")
for exc in exceptions:
# Get parent classes
bases = exc.__bases__[0].__name__
print(f" {exc.__name__} -> {bases}")
# Output:
# ValueError -> Exception
# IndexError -> LookupError
# KeyError -> LookupError
# ZeroDivisionError -> ArithmeticError
# FileNotFoundError -> OSError# Standard exceptions (built into Python)
# These are always available, no import needed
try:
result = 10 / 0
except ZeroDivisionError:
print("Built-in exception handled!")
# Some exceptions need imports but are still "built-in"
import json
try:
json.loads("invalid")
except json.JSONDecodeError:
print("JSON parsing error!")
# You can also create custom exceptions
# (covered in Custom Exceptions lesson)Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep ⢠Build Real ⢠Verify Skills ⢠Launch Forward