Skip to content

Python Error Handling: try, except, raise, and Custom Exceptions

  • Python’s exception hierarchy and the difference between exceptions and errors.
  • Catching exceptions with try/except, scoping with else and finally.
  • Raising, re-raising, and chaining exceptions with raise ... from.
  • Defining custom exception classes for domain-specific errors.
  • Patterns that production code uses to avoid swallowing errors silently.

Python uses exceptions for error signalling — not return codes. When something unexpected happens, code raises an exception. If nothing catches it, the program terminates with a traceback. If you catch it, you decide what to do: log it, retry, return a fallback value, or re-raise with more context.

Good exception handling is specific: catch only what you can handle, let everything else propagate.

Save examples as .py and run with python examples.py (Python 3.9+).

All built-in exceptions inherit from BaseException. The practical split:

BaseException
├── SystemExit # sys.exit() — do not catch unless you're a framework
├── KeyboardInterrupt # Ctrl-C — do not catch unless you need cleanup
└── Exception # catch this family in application code
├── ValueError # bad value for the right type: int("hello")
├── TypeError # wrong type: 1 + "a"
├── KeyError # dict key missing: d["x"] when "x" not in d
├── IndexError # list index out of range
├── AttributeError # object has no such attribute
├── FileNotFoundError # (subclass of OSError)
├── ZeroDivisionError
├── PermissionError # (subclass of OSError)
├── RuntimeError # generic runtime problems
└── ...
def parse_order_amount(raw: str) -> float:
"""Parse a user-supplied amount string. Returns 0.0 on invalid input."""
try:
return float(raw)
except ValueError:
print(f"Cannot parse {raw!r} as a number, defaulting to 0.0")
return 0.0
print(parse_order_amount("149.99")) # 149.99
print(parse_order_amount("abc")) # Cannot parse 'abc' as a number
# 0.0

Catch the most specific exception type possible. except Exception catches too broadly and hides bugs.

def load_order(order_id: str) -> dict:
orders = {"ORD-001": {"amount": 100.0}}
try:
return orders[order_id]
except KeyError:
raise ValueError(f"Order {order_id!r} not found")
def process(order_id: str, raw_amount: str) -> float:
try:
order = load_order(order_id)
multiplier = float(raw_amount)
return order["amount"] * multiplier
except ValueError as e:
print(f"Input error: {e}")
return 0.0
except (TypeError, AttributeError) as e:
# Catch multiple types in a tuple
print(f"Unexpected data: {e}")
return 0.0
import json
from pathlib import Path
def read_config(path: str) -> dict:
"""
Returns config dict, or empty dict if file missing or malformed.
Uses else (runs only if no exception) and finally (runs always).
"""
f = None
try:
f = open(path, encoding="utf-8")
data = json.load(f)
except FileNotFoundError:
print(f"Config not found at {path}, using defaults")
return {}
except json.JSONDecodeError as e:
print(f"Malformed JSON in {path}: {e}")
return {}
else:
# Runs only when no exception was raised in try
print(f"Loaded {len(data)} config keys")
return data
finally:
# Runs regardless of success or failure
if f:
f.close()
config = read_config("config.json")

Prefer with open(path) as f: over manual open/close — it handles finally automatically. The example above uses explicit open to demonstrate finally.

def apply_discount(amount: float, pct: float) -> float:
if not 0.0 < pct <= 1.0:
raise ValueError(f"Discount must be between 0 and 1, got {pct}")
return round(amount * (1 - pct), 2)
print(apply_discount(100.0, 0.10)) # 90.0
apply_discount(100.0, 1.5) # ValueError: Discount must be between 0 and 1, got 1.5

Re-raising the current exception without losing the traceback:

try:
result = apply_discount(-10.0, 0.10)
except ValueError:
print("Caught an error, logging...")
raise # re-raises the same exception with its original traceback

When you catch one exception and raise a different one, use raise NewError(...) from original to preserve the full chain of causes:

def fetch_order_from_db(order_id: str) -> dict:
raise ConnectionError("Database unreachable")
def get_order(order_id: str) -> dict:
try:
return fetch_order_from_db(order_id)
except ConnectionError as e:
raise RuntimeError(f"Cannot retrieve order {order_id!r}") from e
try:
get_order("ORD-001")
except RuntimeError as e:
print(e) # Cannot retrieve order 'ORD-001'
print(e.__cause__) # Database unreachable

The traceback shows both exceptions. Without from e, the connection between the two would be implicit and confusing.

Define custom exceptions for domain-specific errors. This lets callers catch exactly what they care about:

class OrdersPortalError(Exception):
"""Base class for all OrdersPortal exceptions."""
class OrderNotFoundError(OrdersPortalError):
def __init__(self, order_id: str) -> None:
self.order_id = order_id
super().__init__(f"Order {order_id!r} not found")
class InsufficientStockError(OrdersPortalError):
def __init__(self, sku: str, requested: int, available: int) -> None:
self.sku = sku
self.requested = requested
self.available = available
super().__init__(
f"Cannot fulfill {requested} units of {sku!r}: only {available} available"
)
def place_order(order_id: str, sku: str, qty: int) -> None:
stock = {"WIDGET-01": 5}
if sku not in stock:
raise OrderNotFoundError(order_id)
if stock[sku] < qty:
raise InsufficientStockError(sku, qty, stock[sku])
print(f"Order {order_id} placed: {qty} × {sku}")
try:
place_order("ORD-010", "WIDGET-01", 10)
except InsufficientStockError as e:
print(e) # Cannot fulfill 10 units of 'WIDGET-01': only 5 available
print(e.sku, e.requested) # WIDGET-01 10
except OrdersPortalError as e:
print(f"Domain error: {e}")

The base OrdersPortalError class lets callers catch all domain errors with one except clause while still being able to handle specific subtypes separately.

  • Bare except: or except Exception: on every block. This swallows bugs silently. Catch only what you can actually handle; let everything else propagate.
  • Catching BaseException. This catches SystemExit and KeyboardInterrupt, preventing the program from being stopped cleanly.
  • Empty except blocks. except SomeError: pass hides the error completely. At minimum, log it.
  • Raising Exception("message") instead of a specific type. Callers have no way to handle it programmatically without matching the message string.
  • Using exceptions for flow control. Python’s “easier to ask forgiveness than permission” (EAFP) style is idiomatic, but try/except for control flow in hot loops has measurable overhead. Prefer if key in d: over catching KeyError in performance-sensitive code.

1. What is the difference between raise and raise e? raise (bare) re-raises the current exception and preserves the original traceback. raise e raises the exception object e and starts a new traceback from the current line, losing information about where the original exception came from. Almost always use bare raise when re-raising inside an except block.

2. When would you use the else clause on a try block? When there is code that should run only if the try block succeeded and you want it inside the exception-handling context but not mixed with the code that might raise. It makes the intent explicit: “this runs on success”. It is not commonly used but is cleaner than putting success-path code inside the try block where it might accidentally catch exceptions it was not meant to handle.

3. Senior scenario: an OrdersPortal service calls three external APIs — inventory, payment, and shipping. Any of them may be temporarily unavailable. How would you structure the exception handling? Define a custom exception hierarchy (InventoryServiceError, PaymentServiceError, ShippingServiceError) all inheriting from OrdersPortalError. Wrap each API call in a function that catches the client’s exceptions and re-raises as the domain type with raise ... from. At the service boundary, catch each domain exception and decide independently: inventory failure → retry up to 3 times then fail the order; payment failure → fail immediately (do not retry, avoid double-charges); shipping failure → succeed the order but mark it as payment_taken_shipping_pending. This way the calling code handles business logic, and the low-level transport details stay encapsulated.

  • Catch the most specific exception type possible; avoid bare except:.
  • else runs when no exception occurred; finally runs always.
  • Use raise ... from original to chain exceptions and preserve context.
  • Define a custom exception hierarchy rooted at a base class for your application.
  • Re-raise with bare raise to preserve the original traceback.