L4·OOP & Errors

🪵Custom Exceptions & Logging

Raise meaningful errors, chain them, and log instead of print.

raiseexception chainingloggingfinally

§ 1Custom exceptions

Subclass Exception to name your failure cases. Callers can then catch exactly what they expect.

1class InsufficientFunds(Exception):​
2 pass​

§ 2Chaining

raise NewError(...) from err keeps the original cause in the traceback — essential for debugging.

§ 3logging

logging has levels DEBUG < INFO < WARNING < ERROR < CRITICAL, timestamps and handlers. logger.exception() inside except logs the traceback too.

Worked example

1import logging​
2logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")​
3log = logging.getLogger("bank")​
4​
5class InsufficientFunds(Exception):​
6 def __init__(self, need, have):​
7 super().__init__(f"need {need}, have {have}")​
8​
9def withdraw(balance, amount):​
10 if amount > balance:​
11 raise InsufficientFunds(amount, balance)​
12 return balance - amount​
13​
14try:​
15 withdraw(100, 250)​
16except InsufficientFunds as e:​
17 log.warning("withdraw failed: %s", e)​
18finally:​
19 log.info("done")​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Custom exceptions should inherit from:

Lesson test

Take an 8-question test on “Custom Exceptions & Logging” — concepts, output prediction, bug spotting and interview questions.