Exception Chaining & Best Practices
Exception chaining preserves the original error context. Follow best practices: be specific, don't suppress errors silently, and use logging.
10 min•By Priygop Team•Updated 2026
Exception Best Practices
Exception Best Practices
# Exception chaining (raise from)
class DatabaseError(Exception): pass
def query_database():
try:
result = {}["missing_key"]
except KeyError as e:
raise DatabaseError("Query failed") from e
try:
query_database()
except DatabaseError as e:
print(f"DB Error: {e}")
print(f"Caused by: {e.__cause__}")
# Best practices
# 1. Be specific — catch specific exceptions
# BAD:
# try: ... except: pass
# GOOD:
try:
value = int("hello")
except ValueError as e:
print(f"Conversion error: {e}")
# 2. Don't suppress errors silently
# BAD: except: pass
# GOOD: except ValueError: logger.warning("...")
# 3. Use EAFP (Easier to Ask Forgiveness)
data = {"name": "Alice"}
# EAFP (Pythonic)
try:
value = data["age"]
except KeyError:
value = "Unknown"
# vs LBYL (Look Before You Leap)
value = data["age"] if "age" in data else "Unknown"
print(f"Age: {value}")Tip
Tip
Use 'raise from e' to chain exceptions and preserve the original traceback. It helps debugging immensely.
Diagram
Loading diagram…
Catch specific exceptions. Use else for success logic. finally for cleanup. Custom exceptions for your domain.
Common Mistake
Warning
Swallowing exceptions silently with except: pass. At minimum, log the error. Silent failures are the hardest bugs to find.
Practice Task
Note
(1) Chain exceptions with 'raise from'. (2) Create a retry decorator for transient errors. (3) Log exceptions properly.