IndentationError — Easy Examples
Raised when indentation is incorrect
Triggering IndentationError
How IndentationError is raised and how to catch it.
python
# Triggering and catching IndentationError try: exec(" x = 1") except IndentationError as e: print(f"Caught IndentationError: {e}") print(f"Type: {type(e).__name__}")
IndentationError is raised when raised when indentation is incorrect. Always catch specific exceptions rather than bare except clauses.
Handling IndentationError
Basic error handling pattern for IndentationError.
python
# Safe handling pattern def safe_operation(): try: exec(" x = 1") except IndentationError: 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