Error Handling (try/except)
Objective
Handle exceptions gracefully in Python, create custom exceptions, use finally for cleanup, and log errors properly.
Tools & Technologies
tryexceptfinallyraiseExceptionlogging
Key Commands
try: x = int(input())\nexcept ValueError: passraise ValueError('must be positive')except (TypeError, ValueError) as e:finally: f.close()Architecture Overview
flowchart TD
TRY[try block\nexecutes] --> ERROR{Exception\nraised?}
ERROR -->|ValueError| EV[except ValueError\nhandles it]
ERROR -->|TypeError| ET[except TypeError\nhandles it]
ERROR -->|any other| EX[except Exception as e\ngeneral handler]
ERROR -->|no exception| ELSE[else block\noptional]
EV --> FINALLY[finally block\nalways runs]
ET --> FINALLY
EX --> FINALLY
ELSE --> FINALLY
FINALLY --> CONT[Continue / return]
style FINALLY fill:#1a1a2e,stroke:#ffd700,color:#ffd700
Step-by-Step Process
01
Basic try/except
Catch specific exceptions.
# Specific exception
try:
n = int(input('Enter a number: '))
except ValueError as e:
print(f'Invalid input: {e}')
# Multiple exceptions
try:
result = risky_operation()
except (ValueError, TypeError) as e:
print(f'Data error: {e}')
except FileNotFoundError:
print('File not found')
except Exception as e:
print(f'Unexpected error: {e}')
raise # re-raise
02
finally and Custom Exceptions
Ensure cleanup and create domain-specific exceptions.
# finally always runs
try:
f = open('file.txt')
data = f.read()
except IOError as e:
print(f'IO error: {e}')
finally:
f.close() # always called
# Custom exception
class ValidationError(ValueError):
def __init__(self, field, msg):
self.field = field
super().__init__(f'{field}: {msg}')
raise ValidationError('age', 'must be positive')
Challenges & Solutions
- Bare except: catches everything including KeyboardInterrupt — always specify type
- Catching Exception silences unexpected bugs — log or re-raise them
Key Takeaways
- except clause should be as specific as possible — least specific last
- Use context managers (with) instead of try/finally for resource cleanup