Error Handling
try/except/else/finally, raise, and custom exceptions
Skills taught: python.try-except, python.raise, python.custom-exceptions, python.exception-hierarchy
try / except / else / finally
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
# Catching the error object
try:
x = int('not a number')
except ValueError as e:
print(f'Error: {e}') # invalid literal for int()...
# Multiple except clauses
try:
data = {'name': 'Prashant'}
print(data['age']) # KeyError
except KeyError as e:
print(f'Key not found: {e}')
except TypeError as e:
print(f'Type error: {e}')
# else — runs if NO exception occurred
try:
value = int('42')
except ValueError:
print('Not a number')
else:
print(f'Parsed successfully: {value}') # runs here!
# finally — ALWAYS runs
try:
f = open('data.txt')
content = f.read()
except FileNotFoundError:
print('File not found')
finally:
print('Cleaning up...') # always executes
# f.close() would go here (but 'with' is better)
Raising and creating exceptions
# Raise built-in exceptions
def divide(a, b):
if b == 0:
raise ValueError('Divisor cannot be zero')
return a / b
try:
divide(10, 0)
except ValueError as e:
print(e) # Divisor cannot be zero
# Re-raise with context
try:
result = divide(10, 0)
except ValueError as e:
raise RuntimeError('Division failed') from e
# Custom exception classes
class InsufficientFundsError(Exception):
def __init__(self, requested, available):
self.requested = requested
self.available = available
super().__init__(
f'Requested {requested}, but only {available} available'
)
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(amount, self.balance)
self.balance -= amount
acc = BankAccount(100)
try:
acc.withdraw(200)
except InsufficientFundsError as e:
print(e.requested, e.available) # 200 100
print(e) # full message
Common exceptions to know
- ValueError — right type, wrong value: int('abc'), math.sqrt(-1)
- TypeError — wrong type: 'hello' + 42, len(42)
- KeyError — dict key doesn't exist: d['missing']
- IndexError — list index out of range: lst[99]
- AttributeError — object doesn't have that attribute: None.strip()
- FileNotFoundError — file doesn't exist
- ZeroDivisionError — dividing by zero
- ImportError / ModuleNotFoundError — module not found
- StopIteration — iterator exhausted (rarely caught manually)
- RuntimeError — generic 'something went wrong'
Frequently Asked Questions
Should I catch Exception or be more specific?
Be specific. Catching Exception is too broad — it hides programming errors (bugs). Catching the most specific exception you can handle makes your error handling intentional. If you do catch Exception, always log it: logging.exception('Unexpected error') — this preserves the stack trace.
What is 'raise from'?
raise NewError('message') from original_error creates exception chaining — the new error's __cause__ points to the original. Python displays both when showing the traceback. Use it when translating low-level errors to higher-level ones: raise HTTPError('Request failed') from connection_error.