Skip to main content
Albero Academy

Python Exception Handling

Handle errors gracefully with try/except/else/finally, raise exceptions, define custom exception classes, and write robust Python.

Chapter 12Python15 min readBeginner friendly
  • #Python
  • #Exceptions
  • #Error Handling

Code that doesn't handle errors is broken. Python uses exceptions — events that interrupt normal flow when something goes wrong. The trick isn't catching every exception; it's catching the right ones, at the right level, and letting the rest bubble up.

Why exceptions?

Compare two styles of error reporting:

Python
# Old-school C-style: returns a sentinel
def to_int(s):
try:
return int(s)
except ValueError:
return -1
result = to_int("oops")
if result == -1: # easy to forget the check
print("invalid")
# Pythonic: raise on failure, callers handle it
def to_int(s):
return int(s) # raises ValueError automatically
try:
result = to_int("oops")
except ValueError:
print("invalid")

try / except

Python
try:
age = int(input("Age? "))
print(f"You are {age} years old.")
except ValueError:
print("That wasn't a number.")
# Catch the exception object itself
try:
open("missing.txt")
except FileNotFoundError as e:
print(f"Couldn't open: {e}")
print(f"File: {e.filename}")

Multiple except blocks

Python
try:
response = requests.get(url, timeout=5)
data = response.json()
user = data["user"]["name"]
except requests.Timeout:
print("Server took too long.")
except requests.ConnectionError:
print("No network.")
except KeyError as e:
print(f"Unexpected response shape — missing {e}")
except Exception as e: # last resort
print(f"Something else broke: {e}")

You can also catch multiple exceptions in one block:

Python
try:
risky()
except (ValueError, TypeError, KeyError) as e:
print(f"Bad input: {e}")

else and finally

BlockRuns when
tryalways
exceptonly on matching exception
elseonly if try succeeded with no exception
finallyalways — even after return / exception
Python
try:
f = open("data.csv")
except FileNotFoundError:
print("missing file")
else:
process(f) # only if open() succeeded
finally:
f.close() # always — clean up

Raising exceptions

Python
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise ValueError(f"insufficient funds (have {balance})")
return balance - amount
# Re-raise after logging
try:
withdraw(100, 1000)
except ValueError as e:
log.warning(f"withdrawal failed: {e}")
raise # re-raises the same exception
# Chain — keeps the original cause visible
try:
parse(data)
except ValueError as e:
raise ParseError("could not parse input") from e

Custom exception classes

Python
class PaymentError(Exception):
"""Base class for all payment-related failures."""
class InsufficientFunds(PaymentError):
def __init__(self, balance, requested):
super().__init__(f"have {balance}, need {requested}")
self.balance = balance
self.requested = requested
# Now callers can catch the family
try:
process_payment()
except InsufficientFunds as e:
suggest_topup(e.balance, e.requested)
except PaymentError as e:
log.error(e)

Best practices

  • Catch what you can handle. Don't except Exception: just to make a problem disappear.
  • Catch narrowly. except ValueError is better than except Exception.
  • Don't swallow errors. A bare except: pass is almost always a bug waiting to happen.
  • Add context. When re-raising, use from so the original traceback is preserved.
  • Use finally for cleanup only when a context manager (with) won't do.
  • Define custom exception classes for your domain — they read better and let callers catch a category.

Key takeaways

  1. 01Exceptions interrupt control flow — they're better than sentinel return values.
  2. 02Catch the most specific exception class you can. except Exception is a code smell.
  3. 03else runs after try succeeds; finally runs no matter what.
  4. 04raise SomeError('msg') from original_exc preserves the cause chain.
  5. 05Define custom exception classes for your domain — InsufficientFunds reads better than ValueError.
  6. 06Never write `except: pass`. If you really mean it, log first.