Python Exception Handling Cheatsheet
Master Python's try/except/finally syntax and common exceptions.
Exception Hierarchy
| Exception | When it occurs |
|---|---|
ValueError |
Wrong value type |
TypeError |
Wrong data type |
KeyError |
Dict key missing |
IndexError |
List index out of range |
FileNotFoundError |
File doesn't exist |
ZeroDivisionError |
Division by zero |
AttributeError |
Object has no attribute |
ImportError |
Module not found |
PermissionError |
Insufficient permissions |
Code Examples
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
data = int("not a number")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
# Full pattern with else and finally
def read_file(filename):
try:
with open(filename) as f:
return f.read()
except FileNotFoundError:
print(f"File {filename} not found")
return None
except PermissionError:
print("No permission to read")
return None
else:
print("File read successfully") # runs if no exception
finally:
print("Always runs") # cleanup code
# Custom exceptions
class ValidationError(ValueError):
def __init__(self, field, message):
self.field = field
super().__init__(f"{field}: {message}")
def validate_age(age):
if not isinstance(age, int):
raise TypeError(f"Expected int, got {type(age).__name__}")
if age < 0 or age > 150:
raise ValidationError("age", f"Must be 0-150, got {age}")
return True
# Context manager for exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("nonexistent.txt") # silently ignored
Follow me for more Python cheatsheets! 🐍
Follow for more Python content!
喜欢这篇文章?关注获取更多Python自动化内容!
If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.
Top comments (0)