Overview
Python uses exceptions to signal errors and exceptional conditions. Proper handling of these exceptions lets your programs recover gracefully, log useful information, and maintain a clean control flow.
Exceptions
All built‑in exceptions inherit from BaseException. Most user‑visible errors derive from Exception.
class MyError(Exception):
"""Custom error for demonstration"""
pass
Try‑Except
The try block encloses code that may raise an exception. except clauses catch specific exception types.
try:
result = 10 / divisor
except ZeroDivisionError as e:
print('Cannot divide by zero:', e)
except Exception as e:
print('Unexpected error:', e)
Finally
The finally block runs no matter what—useful for cleanup.
file = open('data.txt')
try:
data = file.read()
finally:
file.close()
Else
The else clause runs only if no exception was raised.
try:
value = int(user_input)
except ValueError:
print('Invalid number')
else:
print('You entered', value)
Custom Exceptions
Define your own exception types to convey domain‑specific errors.
class ValidationError(Exception):
def __init__(self, field, msg):
super().__init__(f'{field}: {msg}')
self.field = field
self.msg = msg
Common Patterns
- Validate inputs early and raise
ValueErroror custom exceptions. - Wrap external resources (files, network) in
withstatements or usetry/finallyfor cleanup. - Log exceptions using the
loggingmodule before re‑raising if needed.