IndexError — Easy Examples
Raised when a sequence index is out of range
Triggering IndexError
How IndexError is raised and how to catch it.
python
# Triggering and catching IndexError try: lst = [1, 2, 3]; lst[10] except IndexError as e: print(f"Caught IndexError: {e}") print(f"Type: {type(e).__name__}")
IndexError is raised when raised when a sequence index is out of range. Always catch specific exceptions rather than bare except clauses.
Handling IndexError
Basic error handling pattern for IndexError.
python
# Safe handling pattern def safe_operation(): try: lst = [1, 2, 3]; lst[10] except IndexError: 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