Python Exception Handling: try/except/raise
Part 11 of the Python for Everyone track. Last updated: September 2026.
Exceptions aren't crashes to fear — they're Python's normal way of signaling "something unexpected happened." Master the four-block pattern and you'll write code that fails gracefully instead of mysteriously.
try / except / else / finally
try:
age = int(input("Age: ")) # may raise ValueError
print(f"Next year: {age + 1}")
except ValueError:
print("Please enter a number!")
except (TypeError, OverflowError) as e: # catch multiple, keep the object
print(f"Unexpected problem: {e}")
else:
print("No errors — runs only if try succeeded") # rare but clean
finally:
print("Always runs — cleanup goes here")
Order matters: put specific exceptions before general ones, and never use a bare except: — it swallows KeyboardInterrupt and hides bugs.
raise: throw your own
def withdraw(balance, amount):
if amount < 0:
raise ValueError("amount must be positive")
if amount > balance:
raise ValueError(f"insufficient funds: {balance}")
return balance - amount
try:
withdraw(100, 200)
except ValueError as e:
print(e) # insufficient funds: 100
raise ... from ... chains exceptions when translating low-level errors into domain errors.
Custom exceptions
class PaymentError(Exception):
"""Base for all payment failures in our app."""
pass
class InsufficientFundsError(PaymentError):
pass
try:
raise InsufficientFundsError("balance $10, need $25")
except PaymentError as e: # catches the subclass too
print(f"Payment failed: {e}")
Subclassing Exception (not BaseException) keeps your errors catchable without trapping system exits.
EAFP: it's easier to ask forgiveness
# LBYL (look before you leap) — Java-style
if "key" in config:
value = config["key"]
# EAFP — Pythonic
try:
value = config["key"]
except KeyError:
value = "default"
Python culture prefers EAFP (try first, handle the exception) over LBYL (check everything first) — it's faster in the common case and avoids race conditions.
Key takeaways
- try/except/else/finally — else runs on success, finally always runs.
- Catch specific exceptions; never bare except:.
- raise your own errors; subclass Exception for custom ones.
- Prefer EAFP over LBYL — it's the Pythonic way.
Next in this series: Python Decorators and Generators Explained.
Comments
Post a Comment