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:
# Old-school C-style: returns a sentineldef to_int(s):try:return int(s)except ValueError:return -1result = to_int("oops")if result == -1: # easy to forget the checkprint("invalid")# Pythonic: raise on failure, callers handle itdef to_int(s):return int(s) # raises ValueError automaticallytry:result = to_int("oops")except ValueError:print("invalid")
try / except
try:age = int(input("Age? "))print(f"You are {age} years old.")except ValueError:print("That wasn't a number.")# Catch the exception object itselftry:open("missing.txt")except FileNotFoundError as e:print(f"Couldn't open: {e}")print(f"File: {e.filename}")
Multiple except blocks
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 resortprint(f"Something else broke: {e}")
You can also catch multiple exceptions in one block:
try:risky()except (ValueError, TypeError, KeyError) as e:print(f"Bad input: {e}")
else and finally
| Block | Runs when |
|---|---|
| try | always |
| except | only on matching exception |
| else | only if try succeeded with no exception |
| finally | always — even after return / exception |
try:f = open("data.csv")except FileNotFoundError:print("missing file")else:process(f) # only if open() succeededfinally:f.close() # always — clean up
Raising exceptions
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 loggingtry:withdraw(100, 1000)except ValueError as e:log.warning(f"withdrawal failed: {e}")raise # re-raises the same exception# Chain — keeps the original cause visibletry:parse(data)except ValueError as e:raise ParseError("could not parse input") from e
Custom exception classes
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 = balanceself.requested = requested# Now callers can catch the familytry: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 ValueErroris better thanexcept Exception. - Don't swallow errors. A bare
except: passis almost always a bug waiting to happen. - Add context. When re-raising, use
fromso 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
- 01Exceptions interrupt control flow — they're better than sentinel return values.
- 02Catch the most specific exception class you can. except Exception is a code smell.
- 03else runs after try succeeds; finally runs no matter what.
- 04raise SomeError('msg') from original_exc preserves the cause chain.
- 05Define custom exception classes for your domain — InsufficientFunds reads better than ValueError.
- 06Never write `except: pass`. If you really mean it, log first.
