KeyError — Easy Examples
Raised when a dictionary key is not found
Triggering KeyError
How KeyError is raised and how to catch it.
python
# Triggering and catching KeyError try: d = {}; d["missing"] except KeyError as e: print(f"Caught KeyError: {e}") print(f"Type: {type(e).__name__}")
KeyError is raised when raised when a dictionary key is not found. Always catch specific exceptions rather than bare except clauses.
Handling KeyError
Basic error handling pattern for KeyError.
python
# Safe handling pattern def safe_operation(): try: d = {}; d["missing"] except KeyError: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground