Exception & Error Handling
Handling exceptions lets your program respond to unexpected conditions without crashing.
try / except / finally
try:
value = int(user_input)
except ValueError:
print("Invalid number")
else:
print("Parsed OK")
finally:
print("Always runs")
Raising Exceptions
Use raise to signal an error:
if value < 0:
raise ValueError("value must be non-negative")
Custom Exceptions
Create a specific exception type for domain errors:
class ValidationError(Exception):
pass
raise ValidationError("bad input")
Best Practices
- Catch specific exception types.
- Log errors with context.
- Use
finallyor context managers for cleanup.